Custom Search

Monday, August 30, 2010

php mail() function

When using smtp.gmail.com, gmail will automatically change the From: field to the account.

$receiverName = "receiver name";
$to = "to@hotmail.com";

$senderName = "sender name";
$senderEmail = "sender@hotmail.com";

$subject = "Hi $receiverName, Email From $senderName";

$fileatt = 'image.jpg';

$fileatttype = 'image/jpeg';

$fileattname = 'image.jpg';

$file = fopen( $fileatt, "r" );

$data = fread( $file, filesize( $fileatt ) );

fclose( $file );

$dataencode = chunk_split(base64_encode(file_get_contents('image.jpg')));

$mime_boundary='==Multipart_Boundary_x'.md5(mt_rand()).'x';

//reply to field allows the reply to one sender.
// but from field will still show 2 senders

$headers = "From: $senderEmail \r\n" .
"Reply-To: $senderEmail \r\n".
"MIME-Version: 1.0\r\n" .
"Content-Type: multipart/mixed;" .
"boundary=\"$mime_boundary\";\n\n"
;

$message = "--$mime_boundary\n";
$message .= "Content-Type: text/plain; charset=UTF-8\n";
$message .= "Content-Transfer-Encoding: 8bit\n\n";
$message .= "Thank You.\n\n";

$message .= "--$mime_boundary\n" .
"Content-Type: image/jpeg;\n" .
" name= image.jpg \n" .
"Content-Disposition: attachment;\n" .
" filename= $fileattname \n" .
"Content-Transfer-Encoding: base64\n\n" .
$dataencode . "\n\n" .
"--$mime_boundary--\n";
$message1 = "test";

$mail_sent = @mail( $to, $subject, $message1, $headers."From: $senderName<$senderEmail>");
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";


Will result in the From field being your gmail regardless of what you key in.

However, if you use Yahoo email smtp server, the From: field will not be automatically changed and the result will be your desired one.

change the mail function to the following when using gmail smtp servers:

$mail_sent = @mail( $to, $subject, $message1, $headers."From: $senderName<$to>");

So that your default gmail account will not be seen. However, in the original message properties, it will still be shown for both yahoo and gmail.

No comments: