HomeHowTo › PHP: Sending Mails

PHP: Sending Mails

Here are two code snippets for mail sending in PHP.

1. Sending a simple mail

This is the code to send a simple mail. You only have to set a few variables and then call the mail() function. Unlike everything else, the sender information (name and address) can’t be passed directly — it has to be incorporated into the header. There are more header options available but to keep this simple I only used the necessary ones. The -f parameter is used to define the return path which would be set to the server’s name otherwise.

php_mail
–> View as text

 

2. Sending a mail with attachment

This example is a little bit more complex. It provides an HTML form to upload a file, which will then be sent as an attachment via mail. The mail code itself is put into a custom function sendMail(), so it can be easily called — just passing the necessary data. Since this mail will contain a text and a data portion it has to be in MIME format. To separate the different portions from each other, a unique boundary-string must be defined and put before each portion. Also, a Content-Type and Content-Transfer-Encoding must be defined for each portion. The attachment should be converted to and transferred as Base64 code.

php_mail_with_attachment
–> View as text

 

Notes:

  • Many howtos on the internet use \r\n as a linebreak. I however made the experience that most mail servers are not able to handle those mails. So I just used \n as a linebreak and it has been working fine so far.
  • Content-Transfer-Encoding needs two linebreaks at the end, otherwise it won’t work.
  • Your PHP configuration (usually in /etc/php5/php.ini) must allow file uploads up to a size of 10 mb for this to work. (–> upload_max_filesize, post_max_size, memory_limit).
  • Also, the PHP tmp dir must be writable.

2 Comments.[ Leave a comment ]

  1. Hi, thanks for sharing. I’m wondering if it’s OK to copy some of the text in my site?

  2. Hi, yes you can use the code for your websites. If you use it — as is — for another blog post or tutorial it would be nice if you could link my article. Thanks for asking!

Leave a Comment