In application of tho code, 'nielsvan den berge at hotmail dot com' posted I realised that eol should be \n only :
I changed
$eol = "\r\n";
to
$eol = "\n";
and everything worked fine (at least in mozilla thunderbird).
Mail Functions
Table of Contents
- ezmlm_hash — Calculate the hash value needed by EZMLM
- mail — Send mail
Mail Functions
wallner (www.bemessung.com)
16-May-2008 03:16
16-May-2008 03:16
contact at xpertmailer dot com
10-Apr-2008 05:19
10-Apr-2008 05:19
In reply to anschwartz. If you don't want to install a mail server you can use a free external SMTP mail server to send your mails (like Gmail) with a free PHP Class (like XPertMailer, Zend Framework Mail, PHPMailer or PEAR Mail). Send mail using Gmail and XPertMailer v.4 (http://www.xpertmailer.com/) :
<?php
// path to 'MAIL.php' file from XPM4 package
require_once '/path-to/MAIL.php';
$m = new MAIL; // initialize MAIL class
$m->From('username@gmail.com'); // set From mail address
$m->AddTo('client@destination.net'); // add To mail address
$m->Subject('Hello World!'); // set your mail subject
// set your mail message (text/html)
$m->Html('<b>HTML</b> <u>message</u>.');
// connect to MTA server 'smtp.gmail.com' port '465' via SSL ('tls' encryption)
// with authentication: 'username@gmail.com' and 'password'
// set the connection timeout to 10 seconds, the name of your
// host 'localhost' and the authentication method to 'plain'
// make sure you have OpenSSL module (extension) enable on your php configuration
$c = $m->Connect('smtp.gmail.com', 465, 'username@gmail.com', 'password',
'tls', 10, 'localhost', null, 'plain') or die(print_r($m->Result));
// send mail relay using the '$c' resource connection
echo $m->Send($c) ? 'Mail sent !' : 'Error !';
// disconnect from server
$m->Disconnect();
?>
anschwartz[at sign]earthlink.net
05-Apr-2008 08:09
05-Apr-2008 08:09
Re. the subject of Sendmail on a Windows machine, the following suggestion was made:
<<For Windows users there is a fake sendmail option.
If you have a test server in use running Windows and some kind of WAMP combo (XXAMP, WAMP Server, etc) then you'll notice that the PHP sendmail command (mail()) does not work. Windows simply does not provide the sendmail statement ...
There is a simple trick to get this to work though;
1) Download sendmail.zip from http://glob.com.au/sendmail>>
This works great, but I found that I needed to change the permissions of at least the cmd.exe and maybe also the sendmail.exe. Here's how to do it:
In the windows explorer, right click the name of the file. The cmd.exe is found in your system32 folder; the sendmail.exe is under your c:\wamp folder.
Click the security tab.
If Internet Guest Account is not already listed, then click Add , then Advanced, then Find Now.
Scroll down and select IUSR_machinename (where machinename is the name of your computer)
Click OK twice and return to the security tab.
Select your Internet Guest Account and then click the box under Allow for Read and Execute.
Click OK.
I found that it was not sufficient to do this for just the sendmail.exe, but I also had to do it for the cmd.exe. (Maybe I did not need to do it for the sendmail.exe, but I did not go back and clear the setting. Since I had my mail working, I was happy to move on.)
This plan may leave you vulnerable to attack, however, since now you have allowed a PHP job to run applications on your server. Be careful out there.
sgirard[at]please.no.ROSSPRINT.spam.com
25-Mar-2008 05:08
25-Mar-2008 05:08
Thanks to rob at withoutsin dot com for his authMail routine.
In my case I found it necessary to loop though all the output from the server in response to AUTH LOGIN before I got to the actual username request. Here's what did the trick on my setup:
<?php
for ($i=1; $i<20; $i++) {
fgets($smtpConnect, 4096);
}
?>
You should be able to use the $logArray to find the magic number for your server.
-sean
richard at richard-sumilang dot com
22-Mar-2008 08:12
22-Mar-2008 08:12
If you are using the sendmail app from an exim package or something you don't really need to change the normal parameters PHP gives it (-t -i) as other posts described.
I just added "-f myemail@foo.com" and it worked.
One thing that got me stuck for a few hours was trying to figure out why the return-path was set as the user (user running php) and not what I was setting it with the -f option then I later found at that in order to forcefully set the return-path the user account running the command must be in exim's trusted users configuration! It helps to add trusted_groups as well then everything works fine :)
- Richard Sumilang
pmonjo2000 at yahoo dot com
13-Mar-2008 06:37
13-Mar-2008 06:37
I have found the function provided by nielsvan den berge very useful. However, I would change the following:
<?php
$file_name = substr($attachments[$i]["file"], (strrpos($attachments[$i]["file"], "/")+1));
?>
into
<?php
$file_name = $attachments[$i]["name"];
?>
With this additional column, it is possible to set the name of the attachment to whatever value we want.
mortoray at ecircle-ag dot com
10-Jan-2008 03:35
10-Jan-2008 03:35
Apparently if using the mbstring library, and using overriden functions, the "mail" command appears to use "Content-Transfer-Encoding: BASE64" by default. Which if you combine it with PEAR Mail_Mime you'll get mails that, although they appear RFC compliant, not mailer can read correctly.
To fix this it appears you should add a fixed header in the mail command (this one assumes the pear mime module is 7bit clean, perhaps 8bit would also be fine)
$headers['Content-Transfer-Encoding'] = '7bit';
d
25-Dec-2007 09:39
25-Dec-2007 09:39
When sending html formatted mails to gmail accounts you might notice that the html is shown in plain text. This happens when you send from an unix system and gmail treats the "\r\n" line ends in a wrong way. Use "\n" instead at it will be fine.
Content-Type: text/html; charset=iso-8859-1\n
instead of
Content-Type: text/html; charset=iso-8859-1\r\n
brandon at jhpprojects dot com dot au
14-Nov-2007 05:03
14-Nov-2007 05:03
Sending Email using PHP from Godaddy host
Hi guys this is what you have to use.
You need to use Pear thats already included on the godaddy hosting and then inlcude the mail.php
Here is a function to help you: This will even allow you to send html emails
require_once "Mail.php";
function emailHtml($from, $subject, $message, $to) {
$host = "localhost";
$username = "";
$password = "";
$headers = array ('MIME-Version' => "1.0", 'Content-type' => "text/html; charset=iso-8859-1;", 'From' => $from, 'To' => $to, 'Subject' => $subject);
$smtp = Mail::factory('smtp', array ('host' => $host, 'auth' => false));
$mail = $smtp->send($to, $headers, $message);
if (PEAR::isError($mail))
return 0;
else
return 1;
}
Have fun
Brandon Tapera
Joe
17-Oct-2007 10:20
17-Oct-2007 10:20
SpamAssassin flags it as NO_REAL_NAME because it's looking for a real name with the e-mail address... Instead of passing user@host.com, use "My Name <user@host.com>". This will stop that particular problem.
Also, if you send messages all in HTML, get familiar with Mail/Mime in pear and strip_tags to send a text message identical to the HTML version. This takes care of some other SA problems, and makes it easier for people to read from non-gui mailreaders.
And on a final note, to keep Outlook users from automatically marking your messages as Junk Mail, send a message from Outlook to yourself, look at the headers, and make sure you send as many of the same ones as you can. If outlook thinks your message was sent from another outlook client, it'll score higher on the junk filter.
accius [ at] hotmail [dot ] com
16-Oct-2007 10:28
16-Oct-2007 10:28
I found out the solution for my problem with spamassassin. The sender name and address should be separed with space :
$headers .= "From: ".$fromname." <".$fromaddress.">".$eol;
or
$from = $fromname." <".$fromaddress.">";
ini_set("sendmail_from",$from)
perryv at gmail dot com
13-Oct-2007 05:52
13-Oct-2007 05:52
The ini_set('sendmail_from', $your_from_addr) solution only works when the PHP mailer script is running under Windows. To do a similar solution for *nix OS's, pass the string "-r $your_from_addr" to mail() as the fifth parameter.
accius [at] hotmail [dot] com
12-Oct-2007 09:08
12-Oct-2007 09:08
One small error in nielsvan den berge's code:
ini_set(sendmail_from,$fromaddress) should be written ini_set("sendmail_from",$fromaddress) and ini_restore(sendmail_from) : ini_restore("sendmail_from")
Even with the "sendmail_from" set, SpamAssassin tags the message with NO_REAL_NAME, I didn't find out he solution yet
contact at lattery dot com
01-Oct-2007 10:44
01-Oct-2007 10:44
Brian, in your script text simply add a "\n" to the end of each line of text you want separated. Add two "\n" for a space break between lines. For example:
$message .= "First Name: $firstname\n";
$message .= "Last name: $lastname\n";
will send each of these to your email on separate lines.
peekepichotmailcom
24-Sep-2007 08:47
24-Sep-2007 08:47
Hi all, i recently update my server to another more powerful and since some pop3 servers like "gmail" display my emails like an HTML code :(
After one night, i've found the bug and some info on internet :
"If messages are not received, try using a LF (\n) only. Some poor quality Unix mail transfer agents replace LF by CRLF automatically (which leads to doubling CR if CRLF is used). This should be a last resort, as it does not comply with RFC 2822".
I replace my CRLF separator by LF onyl and all my users received a correct email. PeekEpic.
eflores at sterlingandbaxter dot com
18-Sep-2007 05:29
18-Sep-2007 05:29
I need help. When I send the email the attachments and the multiparts are displayed as text. What am I doing wrong? I have tried the double eols and still have no clue. Here is my code.
<?php
$txt="The report contains locations on the ground for at least 16 weeks and no more than 17 weeks. A summary of last 3 weeks productivity and its average is included. Size".strlen($data);
// Generate a boundary string
$mime_boundary = "<<<--==+X[".md5(time())."]\r\n\r\n";
// Add a multipart boundary above the plain message
$message = "This is a multi-part message in MIME format.\r\n\r\n".
"--".$mime_boundary."\r\n".
"Content-Type: text/plain; charset=\"iso-8859-1\"\r\n".
"Content-Transfer-Encoding: 7bit\r\n".
$txt."\r\n\r\n".
"--".$mime_boundary."\r\n";
// Base64 encode the file data
$data="Dummy Info";
$data = chunk_split(base64_encode($data));
$fileatt_type="application/vnd.ms-excel;";
$fileatt_name="startupLocations.xls";
// Add file attachment to the message
$message .= "Content-Type: ".$fileatt_type."\r\n" .
" name=\"".$fileatt_name."\"\r\n" .
"Content-Transfer-Encoding: base64\r\n" .
"Content-Disposition: attachment;\r\n" .
" filename=\"".$fileatt_name."\"\r\n\r\n" .
$data."\r\n" .
"--".$mime_boundary."\r\n";
// Add the headers for a file attachment
$reportName='Comissions';
unset($sendTo);
$sql = "SELECT * FROM distributionlist left join autoemailtabs
on distributionlist.reporttabid=autoemailtabs.id
WHERE tabname='".$reportName."';";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
$sendTo[] = $row['email'];
}
for($j=0;$j<sizeof($sendTo);$j++){
$headers = "From:eaflores@sterlingandbaxter.com\r\n".
"To:".$sendTo[$j]."\r\n".
"MIME-Version: 1.0\r\n" .
"Content-Type: multipart/mixed;\r\n".
"boundary=\"".$mime_boundary."\"\r\n";
mail($sendTo[$j],' STS Comissions ',$message,$headers);
}//ednFor
//END SEND EMAIL
?>
nielsvandenberge at hotm dot dot dot dot dot com
04-Sep-2007 07:30
04-Sep-2007 07:30
In the post I made about the send_mail() function at 28-Aug-2007 05:15 is a small problem.
the text:
<?php
$headers .= 'MIME-Version: 1.0'.$eol.$eol;
?>
should be replaced by
<?php
$headers .= 'MIME-Version: 1.0'.$eol;
?>
With a double "end of line" you close the header of a block so then the body should start. The Body also ends with two eol's
An e-mail is build up with some blocks, and those blocks can also contain blocks. Every block has a header where is defined what kind of block it is (content-Type). This content can be the texts and attachments for example.
The blocks are separated with a boundary, which is also defined in the header of a block (always starts with two dashes). After the header of a block you should put two "end of lines" (eol) and a boundary. The last block ends with a boundary plus two dashes (so it looks like "--BOUNDARY--") and 2 eol's
When a block contains other blocks (like we did with the HTML/Plain text part), the blocks should be separated by a different boundary then we used before.
So an email will look like:
Mail Header [define boundary "--123"]
2 eol
--123
header block 1 [define boundary "--456"]
2eol
--456
header block 1.1
2eol
content block 1.1
2eol
--456
header block 1.2
2eol
content block 1.2
2eol
--456--
2eol
--123
header block 2
2eol
content block 2
2eol
--123--
2eol
Have fun with it
webmaster at weethet dot nl
01-Sep-2007 02:35
01-Sep-2007 02:35
As mentioned earlier, for Windows users there is a fake sendmail option. A bit more detailed description how to do this is:
If you have a test server in use running Windows and some kind of WAMP combo (XXAMP, WAMP Server, etc) then you'll notice that the PHP sendmail command (mail()) does not work. Windows simply does not provide the sendmail statement ...
There is a simple trick to get this to work though;
1) Download (or use the attached file) sendmail.zip from http://glob.com.au/sendmail/
2) Unzip this in a folder on your c: drive (preferably use a simple path, for example c:\wamp\sendmail -- long filenames could cause problems)
3) Edit your PHP.INI file (note: WAMP users should access their php.ini file from the WAMP menu). Go to the [mail function] section and modify it as such:
[mail function]
; For Win32 only.
;SMTP =
; For Win32 only.
;sendmail_from =
; For Unix only. You may supply arguments as well (default: "sendmail -t -i").
sendmail_path = "C:\wamp\sendmail\sendmail.exe -t"
; Force the addition of the specified parameters to be passed as extra parameters
; to the sendmail binary. These parameters will always replace the value of
; the 5th parameter to mail(), even in safe mode.
;mail.force_extra_paramaters =
.. and save the changes.
4) Open the sendmail.ini and modify the settings to:
[sendmail]
; you must change mail.mydomain.com to your smtp server,
; or to IIS's "pickup" directory. (generally C:\Inetpub\mailroot\Pickup)
; emails delivered via IIS's pickup directory cause sendmail to
; run quicker, but you won't get error messages back to the calling
; application.
smtp_server=mail.yourdomain.com
; smtp port (normally 25)
smtp_port=25
; the default domain for this server will be read from the registry
; this will be appended to email addresses when one isn't provided
; if you want to override the value in the registry, uncomment and modify
default_domain=yourdomain.com
; log smtp errors to error.log (defaults to same directory as sendmail.exe)
; uncomment to enable logging
; error_logfile=sendmail_error.log
; create debug log as debug.log (defaults to same directory as sendmail.exe)
; uncomment to enable debugging
; debug_logfile=sendmail_debug.log
; if your smtp server requires authentication, modify the following two lines
;auth_username=
;auth_password=
; if your smtp server uses pop3 before smtp authentication, modify the
; following three lines
pop3_server=mail.yourdomain.com
pop3_username=you@yourdomain.com
pop3_password=mysecretpassword
; to force the sender to always be the following email address, uncomment and
; populate with a valid email address. this will only affect the "MAIL FROM"
; command, it won't modify the "From: " header of the message content
force_sender=you@yourdomain.com
; sendmail will use your hostname and your default_domain in the ehlo/helo
; smtp greeting. you can manually set the ehlo/helo name if required
hostname=
The optional error and debug logging is recommended when trying this the first time, so you have a clue what goes wrong in case it doesn't work.
Force_sender is also optional, but recommended to avoid confusion on the server end.
Obviously mail.yourdomain.com, you@yourdomain.com, and mysecretpassword should be the relevant info for your SMTP server.
Now restart the WAMP services (mainly Apache so PHP re-reads it's config).
Now you're good to go and use the PHP mail() statement as if you're a Unix user ...
nielsvan den berge at hotmail dot com
28-Aug-2007 03:15
28-Aug-2007 03:15
I updated the function with help of some comments on this page and some research on the internet and this is the final result.
I tested it with MS Outlook, MS Outlook Express, Mozilla Thunderbird, Yahoo webmail, Hotmail, MS Exchange Webaccess and Horde (text-version) and they all gave the desired output with and without attachments.
Spamassassin also accepts this form of sending e-mails, when you use a clean e-mailaddress and body.
<?php
function send_mail($to, $body, $subject, $fromaddress, $fromname, $attachments=false)
{
$eol="\r\n";
$mime_boundary=md5(time());
# Common Headers
$headers .= "From: ".$fromname."<".$fromaddress.">".$eol;
$headers .= "Reply-To: ".$fromname."<".$fromaddress.">".$eol;
$headers .= "Return-Path: ".$fromname."<".$fromaddress.">".$eol; // these two to set reply address
$headers .= "Message-ID: <".time()."-".$fromaddress.">".$eol;
$headers .= "X-Mailer: PHP v".phpversion().$eol; // These two to help avoid spam-filters
# Boundry for marking the split & Multitype Headers
$headers .= 'MIME-Version: 1.0'.$eol.$eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"".$mime_boundary."\"".$eol.$eol;
# Open the first part of the mail
$msg = "--".$mime_boundary.$eol;
$htmlalt_mime_boundary = $mime_boundary."_htmlalt"; //we must define a different MIME boundary for this section
# Setup for text OR html -
$msg .= "Content-Type: multipart/alternative; boundary=\"".$htmlalt_mime_boundary."\"".$eol.$eol;
# Text Version
$msg .= "--".$htmlalt_mime_boundary.$eol;
$msg .= "Content-Type: text/plain; charset=iso-8859-1".$eol;
$msg .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
$msg .= strip_tags(str_replace("<br>", "\n", substr($body, (strpos($body, "<body>")+6)))).$eol.$eol;
# HTML Version
$msg .= "--".$htmlalt_mime_boundary.$eol;
$msg .= "Content-Type: text/html; charset=iso-8859-1".$eol;
$msg .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
$msg .= $body.$eol.$eol;
//close the html/plain text alternate portion
$msg .= "--".$htmlalt_mime_boundary."--".$eol.$eol;
if ($attachments !== false)
{
for($i=0; $i < count($attachments); $i++)
{
if (is_file($attachments[$i]["file"]))
{
# File for Attachment
$file_name = substr($attachments[$i]["file"], (strrpos($attachments[$i]["file"], "/")+1));
$handle=fopen($attachments[$i]["file"], 'rb');
$f_contents=fread($handle, filesize($attachments[$i]["file"]));
$f_contents=chunk_split(base64_encode($f_contents)); //Encode The Data For Transition using base64_encode();
$f_type=filetype($attachments[$i]["file"]);
fclose($handle);
# Attachment
$msg .= "--".$mime_boundary.$eol;
$msg .= "Content-Type: ".$attachments[$i]["content_type"]."; name=\"".$file_name."\"".$eol; // sometimes i have to send MS Word, use 'msword' instead of 'pdf'
$msg .= "Content-Transfer-Encoding: base64".$eol;
$msg .= "Content-Description: ".$file_name.$eol;
$msg .= "Content-Disposition: attachment; filename=\"".$file_name."\"".$eol.$eol; // !! This line needs TWO end of lines !! IMPORTANT !!
$msg .= $f_contents.$eol.$eol;
}
}
}
# Finished
$msg .= "--".$mime_boundary."--".$eol.$eol; // finish with two eol's for better security. see Injection.
# SEND THE EMAIL
ini_set(sendmail_from,$fromaddress); // the INI lines are to force the From Address to be used !
$mail_sent = mail($to, $subject, $msg, $headers);
ini_restore(sendmail_from);
return $mail_sent;
}
?>
timo dot witte at kwick dot de
20-Aug-2007 12:57
20-Aug-2007 12:57
if you wonder how to encode an subject in UTF-8 do it like this:
<?php
mail("timo.witte@kwick.de", "=?UTF-8?B?".base64_encode("also öhm äähh ühh puh ja die Sonderzeichen")."?=", "asbdasdasd bla blabla", $headers);
?>
=UTF-8?B?[Base64 encoded Subject]?=
The B stands for Base64 you could use Q instead of B and encode your UTF-8 string in 7 bit ASCII but base64 is simpler i think.
why encoding?
because you are not allowed to use 8-bit ASCII in mailheaders only 7-bit ASCII is allowed and pure utf-8 uses 8-bit ASCII characters.
Marek Mhling
17-Jul-2007 03:30
17-Jul-2007 03:30
re: mxcl_mail() by Max Howell
http://www.php.net/manual/en/ref.mail.php#72836
Works like a charm, but "iso-9959-1" is likely a typo. I guess "iso-889-1" was meant - though "utf-8" is arguably better anyway.
rob at withoutsin dot com
26-Jun-2007 05:57
26-Jun-2007 05:57
New and Improved - well for gmail users at least. Their SMTP responds differently than other MTA"s. Make sure to enable the pop mail in the gmail account settings first
function authgMail($from, $namefrom, $to, $nameto, $subject, $message)
{
/* your configuration here */
$smtpServer = "tls://smtp.gmail.com"; //does not accept STARTTLS
$port = "465"; // try 587 if this fails
$timeout = "45"; //typical timeout. try 45 for slow servers
$username = "yous@gmail.com"; //your gmail account
$password = "y0u4p@55"; //the pass for your gmail
$localhost = $_SERVER['REMOTE_ADDR']; //requires a real ip
$newLine = "\r\n"; //var just for newlines
/* you shouldn't need to mod anything else */
//connect to the host and port
$smtpConnect = fsockopen($smtpServer, $port, $errno, $errstr, $timeout);
echo $errstr." - ".$errno;
$smtpResponse = fgets($smtpConnect, 4096);
if(empty($smtpConnect))
{
$output = "Failed to connect: $smtpResponse";
echo $output;
return $output;
}
else
{
$logArray['connection'] = "Connected to: $smtpResponse";
echo "connection accepted<br>".$smtpResponse."<p />Continuing<p />";
}
//you have to say HELO again after TLS is started
fputs($smtpConnect, "HELO $localhost". $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['heloresponse2'] = "$smtpResponse";
//request for auth login
fputs($smtpConnect,"AUTH LOGIN" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['authrequest'] = "$smtpResponse";
//send the username
fputs($smtpConnect, base64_encode($username) . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['authusername'] = "$smtpResponse";
//send the password
fputs($smtpConnect, base64_encode($password) . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['authpassword'] = "$smtpResponse";
//email from
fputs($smtpConnect, "MAIL FROM: <$from>" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['mailfromresponse'] = "$smtpResponse";
//email to
fputs($smtpConnect, "RCPT TO: <$to>" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['mailtoresponse'] = "$smtpResponse";
//the email
fputs($smtpConnect, "DATA" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['data1response'] = "$smtpResponse";
//construct headers
$headers = "MIME-Version: 1.0" . $newLine;
$headers .= "Content-type: text/html; charset=iso-8859-1" . $newLine;
$headers .= "To: $nameto <$to>" . $newLine;
$headers .= "From: $namefrom <$from>" . $newLine;
//observe the . after the newline, it signals the end of message
fputs($smtpConnect, "To: $to\r\nFrom: $from\r\nSubject: $subject\r\n$headers\r\n\r\n$message\r\n.\r\n");
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['data2response'] = "$smtpResponse";
// say goodbye
fputs($smtpConnect,"QUIT" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['quitresponse'] = "$smtpResponse";
$logArray['quitcode'] = substr($smtpResponse,0,3);
fclose($smtpConnect);
//a return value of 221 in $retVal["quitcode"] is a success
return($logArray);
}
sevr at mail dot ru
21-Jun-2007 03:02
21-Jun-2007 03:02
It is seems that quotes is needed in the header in charset param. Outlook can't define encoding without them.
$headers = "Content-Type: text/html; charset=\"windows-1251\"\r\n";
$headers .= "MIME-Version: 1.0 ";
rob at withoutsin dot com
12-Jun-2007 08:15
12-Jun-2007 08:15
Having beaten my head against an MCSE for several days over my need for a mail form and his need for "heightened security for IIS" I finally managed to get a working authentication model for Exchange 2003. (note: this will ONLY relay mail to actual users of the Exchange server. i.e. registered email address)
<?
function authMail($from, $namefrom, $to, $nameto, $subject, $message)
{
/* your configuration here */
$smtpServer = "mail.yourdomain.com"; //ip accepted as well
$port = "25"; // should be 25 by default
$timeout = "30"; //typical timeout. try 45 for slow servers
$username = "webform"; //the login for your smtp
$password = "passhere"; //the pass for your smtp
$localhost = "127.0.0.1"; //this seems to work always
$newLine = "\r\n"; //var just for nelines in MS
$secure = 0; //change to 1 if you need a secure connect
/* you shouldn't need to mod anything else */
//connect to the host and port
$smtpConnect = fsockopen($smtpServer, $port, $errno, $errstr, $timeout);
$smtpResponse = fgets($smtpConnect, 4096);
if(empty($smtpConnect))
{
$output = "Failed to connect: $smtpResponse";
return $output;
}
else
{
$logArray['connection'] = "Connected to: $smtpResponse";
}
//say HELO to our little friend
fputs($smtpConnect, "HELO $localhost". $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['heloresponse'] = "$smtpResponse";
//start a tls session if needed
if($secure)
{
fputs($smtpConnect, "STARTTLS". $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['tlsresponse'] = "$smtpResponse";
//you have to say HELO again after TLS is started
fputs($smtpConnect, "HELO $localhost". $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['heloresponse2'] = "$smtpResponse";
}
//request for auth login
fputs($smtpConnect,"AUTH LOGIN" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['authrequest'] = "$smtpResponse";
//send the username
fputs($smtpConnect, base64_encode($username) . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['authusername'] = "$smtpResponse";
//send the password
fputs($smtpConnect, base64_encode($password) . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['authpassword'] = "$smtpResponse";
//email from
fputs($smtpConnect, "MAIL FROM: $from" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['mailfromresponse'] = "$smtpResponse";
//email to
fputs($smtpConnect, "RCPT TO: $to" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['mailtoresponse'] = "$smtpResponse";
//the email
fputs($smtpConnect, "DATA" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['data1response'] = "$smtpResponse";
//construct headers
$headers = "MIME-Version: 1.0" . $newLine;
$headers .= "Content-type: text/html; charset=iso-8859-1" . $newLine;
$headers .= "To: $nameto <$to>" . $newLine;
$headers .= "From: $namefrom <$from>" . $newLine;
//observe the . after the newline, it signals the end of message
fputs($smtpConnect, "To: $to\r\nFrom: $from\r\nSubject: $subject\r\n$headers\r\n\r\n$message\r\n.\r\n");
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['data2response'] = "$smtpResponse";
// say goodbye
fputs($smtpConnect,"QUIT" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['quitresponse'] = "$smtpResponse";
$logArray['quitcode'] = substr($smtpResponse,0,3);
fclose($smtpConnect);
//a return value of 221 in $retVal["quitcode"] is a success
return($logArray);
}
?>
Obviously this function can be expanded upon, and adding attachments should be no real issue based on code found on this page. For me the authentication was the goal; while I had seen many scripts offering it, none seemed to work. I hope this helps someone out there defeat their evil MCSE counterpart
mail [ at ] wietse [ dot ] com
11-Jun-2007 07:35
11-Jun-2007 07:35
[ THIS NOTE IS FOR MY POST ABOUT THE SEND_MAIL() FUNCTION ]
In addition to the already posted PHP Mail-functions, I decided there wasn't one that fitted all my needs, so I wrote my own. I have tested it, and I use it at a Windows 2000 server, but I don't think it won't function at *nix.
Usage:
send_mail(string $MailTo, string $SenderName, string $SenderMail, string $Subject, string-or-path $Mailcontent [, string $Attachment ] [, string $Servername ] [, string $nohtml])
The function returns true or false, depending on if the E-mail has been sent succesfully.
Note 1: $Mailcontent can be a string OR a path to a file.
Note 2: Function works without attachment too
Note 3: Function works to Hotmail
Note 4: Function needs PHP module [ mime_magic ] to detect attachment-type!
mail [ at ] wietse [ dot ] com
11-Jun-2007 07:34
11-Jun-2007 07:34
<?php
function send_mail($MailTo = "", $SenderName = "Sender", $SenderMail = "no@reply.error", $Subject = "", $Mailcontent = "no.file", $Attachment = "no.file", $Servername = "PHPMAILSERVER", $nohtml = "[ This message should be viewed in HTML. This is a degraded version! ]"){
if(strtoupper(substr(PHP_OS,0,3)=='WIN')){
$eol="\r\n";
$sol="\n";
}elseif(strtoupper(substr(PHP_OS,0,3)=='MAC')){
$eol="\r";
}else{
$eol="\n";
}
if(!isset($sol)){
$sol = $eol;
}
$Momentn = mktime().".".md5(rand(1000,9999));
$f_name = $Attachment;
$handle = fopen($f_name, 'rb');
$f_contents = @fread($handle, filesize($f_name));
$f_contents = @base64_encode($f_contents);
if($handle){
$sendfile = true;
if(ini_get('mime_magic.debug')){
$Bestype = @mime_content_type($Attachment);
}else{
$Bestype = 'application/octet-stream';
}
if(!$Bestype){
$Bestype = 'application/octet-stream';
}
$file_realname = explode("/", $Attachment);
$file_realname = $file_realname[count($file_realname)-1];
$file_realname = explode("\\", $file_realname);
$file_realname = $file_realname[count($file_realname)-1];
}
@fclose($handle);
$Mailcontentstri = explode($sol, $Mailcontent);
$Mailcontentstrip = strip_tags($Mailcontentstri[0]);
if(@file_exists($Mailcontentstrip)){
ob_start();
if(require($Mailcontent)){
$body = ob_get_contents();
}
ob_end_clean();
}else{
if(count($Mailcontentstri) < 2){
$body = "Error loading file!";
$error = true;
}else{
$body = $Mailcontent;
}
}
$Textmsg = eregi_replace("<br(.{0,2})>", $eol, $body);
$Textmsg = eregi_replace("</p>", $eol, $Textmsg);
$Textmsg = strip_tags($Textmsg);
$Textmsg = $nohtml.$eol.$eol.$Textmsg;
$headers .= 'To: '.$MailTo.' <'.$MailTo.'>'.$eol;
$headers .= 'From: '.$SenderName.' <'.$SenderMail.'>'.$eol;
$headers .= "Message-ID: <".$Momentn."@".$Servername.">".$eol;
$headers .= 'Date: '.date("r").$eol;
$headers .= 'Sender-IP: '.$_SERVER["REMOTE_ADDR"].$eol;
$headers .= 'X-Mailser: iPublications Adv.PHP Mailer 1.6'.$eol;
$headers .= 'MIME-Version: 1.0'.$eol;
$bndp = md5(time()).rand(1000,9999);
$headers .= "Content-Type: multipart/mixed; $eol boundary=\"".$bndp."\"".$eol.$eol;
$msg = "This is a multi-part message in MIME format.".$eol.$eol;
$msg .= "--".$bndp.$eol;
$bnd = md5(time()).rand(1000,9999);
$msg .= "Content-Type: multipart/alternative; $eol boundary=\"".$bnd."\"".$eol.$eol;
$msg .= "--".$bnd.$eol;
$msg .= "Content-Type: text/plain; charset=iso-8859-1".$eol;
$msg .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
$msg .= $Textmsg.$eol;
$msg .= "--".$bnd.$eol;
$msg .= "Content-Type: text/html; charset=iso-8859-1".$eol;
$msg .= "Content-Transfer-Encoding: 8-bit".$eol.$eol;
$msg .= $body.$eol;
$msg .= "--".$bnd."--".$eol.$eol;
if(isset($sendfile)){
$msg .= "--".$bndp.$eol;
$msg .= "Content-Type: $Bestype; name=\"".$file_realname."\"".$eol;
$msg .= "Content-Transfer-Encoding: base64".$eol;
$msg .= "Content-Disposition: attachment;".$eol;
$msg .= " filename=\"".$file_realname."\"".$eol.$eol;
$f_contents = chunk_split($f_contents);
$msg .= $f_contents.$eol;
}
$msg .= "--".$bndp."--";
if(!isset($error)){
if(@mail($MailTo, $Subject, $msg, $headers)){
return true;
}else{
return false;
}
}else{
return false;
}
}
?>
Pop
20-May-2007 02:03
20-May-2007 02:03
If sendmail on your linux server is configured with options:
sendmail -t -i
you may have problems sending mail if you put something like this in your header
<?
$headers .= "Return-Path: MyName <myname@myhost.com> /n";
?>
nstead use
<?
$headers .= "Reply-To: MyName <myname@myhost.com> /n";
?>
Geoff in Montreal
01-May-2007 10:07
01-May-2007 10:07
Here is a PHP Mail Multipart/Alternative (Plain Text and HTML) code for *nix servers (Unix Like Servers)... if you are hosted on a windows server, simply replace all "\n" or "\n\n" in the below code to "\r\n" or "\r\n\r\n" respectively.
This code is for anyone who has already written an HTML page for their PHP mail... there are several PHP > HTML free translators on the internet. You may use one of them to translate your HTML code to PHP to insert into the following code. All there needs to change is to place a backslash before any quotations (EX: ... confirm that \"Our Company\" has ...), and to end each line with a newline character (EX: \n )...
This code method has been successfully tested with Apple Mail, Microsoft Outlook, G-Mail, and Yahoo Mail. I hope this helps out anyone that is writing a multipart/alternative PHP mailer script.
<?php
# -=-=-=- PHP FORM VARIABLES (add as many as you would like)
$name = $_POST["name"];
$email = $_POST["email"];
$invoicetotal = $_POST["invoicetotal"];
# -=-=-=- MIME BOUNDARY
$mime_boundary = "----Your_Company_Name----".md5(time());
# -=-=-=- MAIL HEADERS
$to = "$email";
$subject = "This text will display in the email's Subject Field";
$headers = "From: Our Company <company@ourcompany.com>\n";
$headers .= "Reply-To: Our Company <company@ourcompany.com>\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/alternative; boundary=\"$mime_boundary\"\n";
# -=-=-=- TEXT EMAIL PART
$message = "--$mime_boundary\n";
$message .= "Content-Type: text/plain; charset=UTF-8\n";
$message .= "Content-Transfer-Encoding: 8bit\n\n";
$message .= "$name:\n\n";
$message .= "This email is to confirm that \"Our Company\" has received your order.\n";
$message .= "Please send payment of $invoicetotal to our company address.\n\n";
$message .= "Thank You.\n\n";
# -=-=-=- HTML EMAIL PART
$message .= "--$mime_boundary\n";
$message .= "Content-Type: text/html; charset=UTF-8\n";
$message .= "Content-Transfer-Encoding: 8bit\n\n";
$message .= "<html>\n";
$message .= "<body style=\"font-family:Verdana, Verdana, Geneva, sans-serif; font-size:14px; color:#666666;\">\n";
$message .= "$name:<br>\n";
$message .= "<br>\n";
$message .= "This email is to confirm that \"Our Company\" has received your order.<br>\n";
$message .= "Please send payment of $invoicetotal to our company address.<br>\n\n";
$message .= "<br>\n";
$message .= "Thank You.<br>\n\n";
$message .= "</body>\n";
$message .= "</html>\n";
# -=-=-=- FINAL BOUNDARY
$message .= "--$mime_boundary--\n\n";
# -=-=-=- SEND MAIL
$mail_sent = @mail( $to, $subject, $message, $headers );
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
Geoff Montreal
30-Apr-2007 04:29
30-Apr-2007 04:29
i strongly feel that internet site developers should exclusively use UTF-8 text encoding / character setting over ISO-8859-1... UTF-8 is universal and will display all characters as they were meant to be displayed, whereas ISO-8859-1 is prone to garbled text.
<?php
$message .= "Content-Type: text/plain; charset=UTF-8\n";
?>
~ and/or ~
<?php
$message .= "Content-Type: text/html; charset=UTF-8\n";
?>
note: above code for *nix servers.
mark at markkahn dot com
06-Apr-2007 03:54
06-Apr-2007 03:54
i tried out 3 different scripts, and played with them for a few hours. Ugh.
Max Howell's mxcl mail function worked right off the bat - attachments, and body. using RH + php 4.4.
thanks max!
grass ät leht dot ee
20-Mar-2007 10:07
20-Mar-2007 10:07
something that worked for my outlook express...
dnx 4 your code "nielsvandenberge at hotmail dot com
"
but
if you just swich the text part into first and attachment part into second place, Outlook Express 6 reads it just fine
otherwise it creates a textfile of the text content....
admin at seoandstuff dot com
15-Mar-2007 04:25
15-Mar-2007 04:25
I just spent a few hours working on getting a simple html formatted email to work on outlook. This is the end result:
<?php
$body="<em>HTML</em> formatted <strong>Message</strong";
$headers = "From: info@example.com \r\n";
$headers.= "Content-Type: text/html; charset=ISO-8859-1 ";
$headers .= "MIME-Version: 1.0 ";
/*notice there aren't any \r\n after the second two header additions. This is what made this version work correctly*/
mail("john@example.com", "An HTML Message", $body, $headers);
?>
br at winf dot at
27-Feb-2007 12:07
27-Feb-2007 12:07
The example function by nielsvandenberge at hotmail dot com is nice, but some Mail Programs (e.g. Outlook Express, etc) do have problems and do not display any text or html of the mailbody - only as a separate attachment.
The main problem is that the multipart/alternative part is not bounded correctly (a problem that Outlook and other newer mailers seem to ignore). To make the function compatible to older/standard mail-programs simply add a second mime boundary, which marks the bounds of the alternative parts:
<?
$mime_boundary_2 = "1_".$mime_boundary;
$msg .= "Content-Type: multipart/alternative; boundary=\"".$mime_boundary_2."\"".$eol;
# Text Version
$msg .= "--".$mime_boundary_2.$eol;
$msg .= "Content-Type: text/plain; charset=iso-8859-1".$eol;
$msg .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
$msg .= strip_tags(str_replace("<br>", "\n", $body)).$eol.$eol;
# HTML Version
$msg .= "--".$mime_boundary_2.$eol;
$msg .= "Content-Type: text/html; charset=iso-8859-1".$eol;
$msg .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
$msg .= $body.$eol.$eol;
# New Subboundary Finished
$msg .= "--".$mime_boundary_2."--".$eol.$eol;
# Top-Boundary Finished
$msg .= "--".$mime_boundary."--".$eol.$eol;
?>
The above snippet also corrects the missing second eol after Content-Transfer-Encoding: 8bit.
jo at camindo de
06-Feb-2007 09:26
06-Feb-2007 09:26
If you have programmed headers do not adopt post-values unfiltered!!
Often used in scripts, and often abused by spam mailings:
$headers = "From: {$email}";
If somebody posts email="me@example.com
Bcc:someone1@example.com,someoneelse@example.com,..."
(with linebreak behind me@example.com)
You get following headers:
From: me@example.com
Bcc:someone1@example.com,someoneelse@example.com,...
Max Howell
02-Feb-2007 04:54
02-Feb-2007 04:54
I find this a useful function, and it's a lot easier to read and edit than the proceeding set. Many thanks to the proceeding set though, since they taught me how to do it!
<?php
function mxcl_mail( $subject, $message )
{
ob_start();
print_r( $GLOBALS );
$teh_globals = chunk_split( base64_encode( ob_get_clean() ) ); // base 64 encode
$date = date( 'r' );
$phpversion = phpversion();
$boundary = md5( time() );
$filename = '$GLOBALS.txt';
$headers = <<<END
From: $_SERVER[PHP_SELF] <php@$_SERVER[SERVER_NAME]>
Date: $date
X-Mailer: PHP v$phpversion
MIME-Version: 1.0
Content-Type: multipart/related; boundary="$boundary"
END;
$message = <<<END
--$boundary
Content-Type: text/plain; charset="iso-9959-1"
Content-Transfer-Encoding: 7bit
$message
--$boundary
Content-Type: octet-stream; name="$filename"
Content-Disposition: attachment; filename="$filename"
Content-Transfer-Encoding: base64
$teh_globals
--$boundary--
END;
mail( 'webmaster@example.com', $subject, $message, $headers );
}
?>
pbglez at hotmail dot com
30-Jan-2007 11:59
30-Jan-2007 11:59
I think the easiest way to make correct attachments is checking The Official MIME Specification: http://www.hunnysoft.com/mime/ (Of course it isnt the only web page where you can find it ).
I found there an example than truly helped me to make correct attachments:
Appendix A -- A Complex Multipart Example
What follows is the outline of a complex multipart message. This
message contains five parts that are to be displayed serially: two
introductory plain text objects, an embedded multipart message, a
text/enriched object, and a closing encapsulated text message in a
non-ASCII character set. The embedded multipart message itself
contains two objects to be displayed in parallel, a picture and an
audio fragment.
MIME-Version: 1.0
From: Nathaniel Borenstein <nsb@nsb.fv.com>
To: Ned Freed <ned@innosoft.com>
Date: Fri, 07 Oct 1994 16:15:05 -0700 (PDT)
Subject: A multipart example
Content-Type: multipart/mixed;
boundary=unique-boundary-1
This is the preamble area of a multipart message.
Mail readers that understand multipart format
should ignore this preamble.
If you are reading this text, you might want to
consider changing to a mail reader that understands
how to properly display multipart messages.
--unique-boundary-1
... Some text appears here ...
[Note that the blank between the boundary and the start
of the text in this part means no header fields were
given and this is text in the US-ASCII character set.
It could have been done with explicit typing as in the
next part.]
--unique-boundary-1
Content-type: text/plain; charset=US-ASCII
This could have been part of the previous part, but
illustrates explicit versus implicit typing of body
parts.
--unique-boundary-1
Content-Type: multipart/parallel; boundary=unique-boundary-2
--unique-boundary-2
Content-Type: audio/basic
Content-Transfer-Encoding: base64
... base64-encoded 8000 Hz single-channel
mu-law-format audio data goes here ...
--unique-boundary-2
Content-Type: image/jpeg
Content-Transfer-Encoding: base64
... base64-encoded image data goes here ...
--unique-boundary-2--
--unique-boundary-1
Content-type: text/enriched
This is <bold><italic>enriched.</italic></bold>
<smaller>as defined in RFC 1896</smaller>
Isn't it
<bigger><bigger>cool?</bigger></bigger>
--unique-boundary-1
Content-Type: message/rfc822
From: (mailbox in US-ASCII)
To: (address in US-ASCII)
Subject: (subject in US-ASCII)
Content-Type: Text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: Quoted-printable
... Additional text in ISO-8859-1 goes here ...
--unique-boundary-1--
Say_Ten
16-Jan-2007 10:45
16-Jan-2007 10:45
Nice example script, although please note that:
$msg .= "Content-Transfer-Encoding: 8bit".$eol;
Should be:
$msg .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
Francesco Piraneo G.
09-Jan-2007 01:52
09-Jan-2007 01:52
Please note that the 'sendmail_from' parameter is used also on php running under linux, not only under Windows as stated on the documentation.
Webmail services and some spam washer software kill messages without the "From" field properly set.
Try the following:
ini_set(sendmail_from,$fromaddress); // the INI lines are to force the From Address to be used !
mail($emailaddress, $emailsubject, $msg, $headers);
...as correctly reported by nielsvandenberge at hotmail dot com.
For further info: fpiraneo at gmail dot com
nielsvandenberge at hotmail dot com
09-Jan-2007 10:44
09-Jan-2007 10:44
I edited the code of genius Jon (thank you!) a bit and made an easy function to send multiple attachments with one e-mail. I stripped the HTML tags for the text-version, but haven't tested that.
The attachments variable of the function is a 2-dimensional array which should contain the keys "file" and "content_type".
I tested it with MS Outlook.
<?php
function send_mail($emailaddress, $fromaddress, $emailsubject, $body, $attachments=false)
{
$eol="\r\n";
$mime_boundary=md5(time());
# Common Headers
$headers .= 'From: MyName<'.$fromaddress.'>'.$eol;
$headers .= 'Reply-To: MyName<'.$fromaddress.'>'.$eol;
$headers .= 'Return-Path: MyName<'.$fromaddress.'>'.$eol; // these two to set reply address
$headers .= "Message-ID: <".$now." TheSystem@".$_SERVER['SERVER_NAME'].">".$eol;
$headers .= "X-Mailer: PHP v".phpversion().$eol; // These two to help avoid spam-filters
# Boundry for marking the split & Multitype Headers
$headers .= 'MIME-Version: 1.0'.$eol;
$headers .= "Content-Type: multipart/related; boundary=\"".$mime_boundary."\"".$eol;
$msg = "";
if ($attachments !== false)
{
for($i=0; $i < count($attachments); $i++)
{
if (is_file($attachments[$i]["file"]))
{
# File for Attachment
$file_name = substr($attachments[$i]["file"], (strrpos($attachments[$i]["file"], "/")+1));
$handle=fopen($attachments[$i]["file"], 'rb');
$f_contents=fread($handle, filesize($attachments[$i]["file"]));
$f_contents=chunk_split(base64_encode($f_contents)); //Encode The Data For Transition using base64_encode();
fclose($handle);
# Attachment
$msg .= "--".$mime_boundary.$eol;
$msg .= "Content-Type: ".$attachments[$i]["content_type"]."; name=\"".$file_name."\"".$eol;
$msg .= "Content-Transfer-Encoding: base64".$eol;
$msg .= "Content-Disposition: attachment; filename=\"".$file_name."\"".$eol.$eol; // !! This line needs TWO end of lines !! IMPORTANT !!
$msg .= $f_contents.$eol.$eol;
}
}
}
# Setup for text OR html
$msg .= "Content-Type: multipart/alternative".$eol;
# Text Version
$msg .= "--".$mime_boundary.$eol;
$msg .= "Content-Type: text/plain; charset=iso-8859-1".$eol;
$msg .= "Content-Transfer-Encoding: 8bit".$eol;
$msg .= strip_tags(str_replace("<br>", "\n", $body)).$