Sending HTML Email in php? - php

Here is the code.
$to = 'youraddress#example.com';
$subject = 'Test HTML email';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster#example.com\r\nReply-To: webmaster#example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/alternative; boundary=\"PHP-alt-".$random_hash."\"";
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
Hello World!!!
This is simple text email message.
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>
--PHP-alt-<?php echo $random_hash; ?>--
<?
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = #mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
I don't follow it well. expect someone can do me a favor.
Why should I generate a random hash?
Why I must add boundary string and mime type specification to header?
Why use ob_start();?
4.
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
What are those lines meaning? Could I delete them? Thank you.

Generating a random hash is to avoid it colliding with your content.
A "boundary string" tells the email clients where headers start and stop and where the actual email contents start. Since you want to send HTML email, you must specifically tell the email client it will be receiving HTML, not just any content.
Otherwise the HTML and stuff will be sent directly to the browser, ie, the user viewing your site. Instead you want to store the HTML in a variable and use it instead.
Content-Type tells the email client what kind of content you are sending and how it is encoded.
Of course you cannot delete them. It would be like sending you a PDF file without saying it is a PDF and without a proper extension - you won't know what to do with it.
Note
Emails, websites, anything which has a structure (including most files) usually are laid out in a structure of "header" and "body".
The header tells the file reader what to expect in the "body". The "body" is the actual content the reader should do something with.

I am not certain why the random hash is used here, but I think it is just additional safety to ensure a unique boundary string, preventing name collisions between parts.
As to the content-type: you need to specify that to tell the mail client that it should render HTML, and to indicate that your message is multipart. Multipart means there's more than one part, in your case a text-based part and a HTML part.
The boundary part is used to separate the contents of one part form the contents of another part, and from the header.
Using the PHP Output Buffer (ob_start and ob_end_clean) is not necessary at all, you can also just enter strings using quotes or using HEREDOC. An advantage of using the output buffer is that you can end the PHP (using ?>) and have your IDE help you writing HTML. Make sure to add ob_end_clean(); though, it is not yet in your code.

You don't have to. It's just that it makes things easier: the delimiter must be a string that's not part of the mail content.
You need a boundary to split the message in parts. An e-mail message is nothing else that a stream of characters. You need a MIME type so the e-mail client can know what each part contains. Otherwise, it could not know whether it's HTML or not (or a JPEG picture, or a PowerPoint presentation...)
Honestly, it looks like an overcomplicate replacement for regular string assignments. Rather than doing $message = 'Hello World!';, it prints Hello World! to standard output and captures the standard output into a variable.
These lines mean that you are finishing one part of the message and you are starting a new one that contains HTML. You can delete them if you don't want to add another message part that contains HTML but... isn't that what you want to do?

Related

How can I send a non-html-email in bold?

I want to send a simple email in php.
Is it possible to make the Second Line of Text in bold without using html mail?
<?php
$msg = "First line of text\nSecond line of text";
mail("someone#example.com","My subject",$msg);
?>
You can't bold or format in any way inside a plain old text email (one which has a MIME type of text/plain). That's why there is such a thing as HTML (MIME type of text/html) formating for email.
FYI, in setting the MIME type to HTML is specified by Content-Type: text/html; charset=UTF-8

PHP: =0D, =A20 symbols

After obtaining info from an email body, I have a lot of symbols such as =0D, =A20, etc... How can I remove them? I do not want to use
$body = str_replace('=A20', '', $body);
because if the email body actually contains that it will be replaced.
Any ideas? Thanks!
Don't replace them to nothing - thoose characters aren't nothing, they are part of the text.
E-mail messages aren't plain text, they are encoded. Thoose examples are part of the quoted-printable encoding, which you can identify by the
Content-Transfer-Encoding: quoted-printable
line at the beginning of the e-mail message.
And php has a method to decode it

How can I send email with UTF-8 encoding?

I have inherited a script that sends some content out in three languages (all on same content - repeated) however when recieved the content characters are broken for what i assume is a UTF-8 issue.
Am i right all i need to do is change the charset part to utf-8, or does anything else need to change like the 7bit part ?
you can see where I inserted one UTF-8 reference (not tested yet)
there was something here http://bitprison.net/php_mail_utf-8_subject_and_message which seems to reference base encoding, but I'm not sure if I need that here ?
// Contruct message body.
$body = "";
// Add message for non-mime clients.
$body .= "This is a multi-part message in MIME format.\n";
// Add text body.
$body .= "\n--$boundary\nContent-Type: text/plain; charset=UTF-8; format=flowed\nContent-Transfer-Encoding: 7bit\n\n" . $textContent;
// Add HTML body.
$body .= "\n--$boundary\nContent-Type: text/html; charset=ISO-8859-1; format=flowed\nContent-Transfer-Encoding: 7bit\n\n" . $htmlContent;
mail( $row["email"], "Update Your ArtsDB Listing", $body, $headers );
I looked on another post on here for an a example.
$body .= "\n--$boundary\nContent-Type: text/plain; charset=UTF-8; format=flowed\nContent-Transfer-Encoding: 8bit\n\n" . $textContent;
// Add HTML body.
$body .= "\n--$boundary\nContent-Type: text/html; charset=UTF-8; format=flowed\nContent-Transfer-Encoding: 8bit\n\n" . $htmlContent;
You are using Content-Type: text/plain; charset=UTF-8 to tell the mail reader that such message part uses UTF-8, which is fine, but... What does the $textContent variable contain? That's the important bit. According to Content-Transfer-Encoding: 7bit, it's a 7 bit encoding so it can't be raw UTF-8. However, you are not using any of the usual 7-bit encodings used for e-mail. Otherwise, there would be a (e.g.) Content-Transfer-Encoding: quoted-printable header.
To sum up, you need to:
Have a source string that contains valid UTF-8.
Pick a encoding for the transfer, such as quoted_printable_encode().
Add a header to tell which transfer encoding you chose.
You could also send the raw UTF-8 as-is and set Content-Transfer-Encoding: 8bit but I would not recommend it. You risk breaking the SMTP standard just by sending very long lines. Also, you have no idea of what kind of legacy programs this will go through.
E-mail is harder than it seems, that's why sooner or later you end up using a third-party library: PHP Mailer, Swift Mailer, PEAR Mail...
Content-Transfer-Encoding: 7bit
This makes no sense - there is no direct mapping between 7bit data and an 8+bit representation. You need to change the mime headers to state what encoding you are using.
For SMTP the transfer encoding should be a 7 bit ascii charset. To change your utf8 data you need to encode this - common encodings are base64 and quoted printable (PHP provides encode and decode fns for both).
Why not just use a good lib like phpmailer or swiftmailer

Proper PHP way to parse email attachments from EML format

I have a file containing an email in "plain text MIME message format". I am not sure if this is the EML format. The email contains an attachment and I want to extract the attachment and create those files again. This is how the attachment part looks like -
...
...
Receive, deliver details
...
...
From: sac ascsac <sacsac#sacascsac.ascsac>
Date: Thu, 20 Jan 2011 18:05:16 +0530
Message-ID: <AANLkTimmSL0iGW4rA3tvSJ9M3eT5yZLTGsqvCvf2fFC3#mail.gmail.com>
Subject: Test attachments
To: ascsacsa#ascsac.com
Content-Type: multipart/mixed; boundary=20cf3054ac85d97721049a465e12
--20cf3054ac85d97721049a465e12
Content-Type: multipart/alternative; boundary=20cf3054ac85d97717049a465e10
--20cf3054ac85d97717049a465e10
Content-Type: text/plain; charset=ISO-8859-1
hello this is a test mail. It contains two attachments
--20cf3054ac85d97717049a465e10
Content-Type: text/html; charset=ISO-8859-1
hello this is a test mail. It contains two attachments<br>
--20cf3054ac85d97717049a465e10--
--20cf3054ac85d97721049a465e12
Content-Type: text/plain; charset=US-ASCII; name="simple_test.txt"
Content-Disposition: attachment; filename="simple_test.txt"
Content-Transfer-Encoding: base64
X-Attachment-Id: f_gj5n2yx60
aGVsbG8gd29ybGQKYWMgYXNj
...
encoded things here
...
ZyBmZyAKCjIKNDIzCnQ2Mwo=
--20cf3054ac85d97721049a465e12
Content-Type: application/x-httpd-php; name="oscomm_backup_code.php"
Content-Disposition: attachment; filename="oscomm_backup_code.php"
Content-Transfer-Encoding: base64
X-Attachment-Id: f_gj5n5gxn1
PD9waHAKCg ...
...
encoded things here
...
X2xpbmsoRklMRU5BTUVfQkFDS1VQKSk7Cgo/Pgo=
--20cf3054ac85d97721049a465e12--
I can see that the part between X-Attachment-Id: f_gj5n2yx60 and ZyBmZyAKCjIKNDIzCnQ2Mwo=, both including
is the content of the first attachment. I want to parse those attachments (file names and contents and create those files).
I got this file after parsing a dbx format file using a DBX Parser class available in PHP classes.
I searched in many places and did not find much discussion regarding this here in SO other than Script to parse emails for attachments. May be I missed some terms while searching. In that answer it is mentioned -
you can use the boundries to extract
the base64 encoded information
But I am not sure which are the boundaries and how exactly to use the boundaries? There already must be some libraries or some well defined method of doing this. I guess I will commit many mistakes if I try reinventing the wheel here.
There's an PHP Mailparse extension, have you tried it?
The manual way would be, process the mail line by line. When you hit your first Content-Type header (this one in your example):
Content-Type: multipart/mixed; boundary=20cf3054ac85d97721049a465e12
You have the boundary. This string is used as the boundary between your multiple parts (that's why they call it multipart).
Everytime a line starts with the dashes and this string, a new part begin. In your example:
--20cf3054ac85d97721049a465e12
Every part will start with headers, a blank line, and content. By looking at the content-type of the headers you can determine which are attachments, what their type is and their filename.
Read the whole content, strip the spaces, base64_decode it, and you've got the binary contents of the file. Does this help?

How to pull html encoding from email data using PHP

I'm working with emails and want to display the html in the browser, I'm not sure how to deal with the encoding. I want to extract the html to display it in the html browser. The way I plan on doing this is using an html parser on the entire email parsing the data inbetween the tags in the html section. Is there an easier/more efficient way to do this?
Here's text encoding
------=_Part_29856965_540743623.1285814590176
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: 7bit
Here's the html encoding
------=_Part_29856965_540743623.1285814590176
Content-Type: text/html; charset=ISO-8859-1
Content-Transfer-Encoding: 7bit
You can have a look at the ezComponents - Mail component. It has a lot of operations for building and using a MIME
http://ezcomponents.org/docs/tutorials/Mail

Categories