I recently had the need to take a name from a form submission and use it as the display name of the “From” address of an email sent through PHP’s mail() function. For an address like Toby Example <firstname.lastname@example.org>, the display name is the Toby Example part.
I recently had to set up a PHP script to send an email with an attachment. With the current version of our CMS, we have swiftmailer available, which would make this easy, but for this site, I didn’t have it easily available. I considered bringing it in, but since this was just a simple script, I decided to give a go at doing it directly with PHP’s built in mail() function. I found an answer on StackOverflow to guide me. Many respondents to that question recommended just using a library, but the answers that didn’t seemed reasonable.
It took me a number of failed attempts to get the headers and line-breaks just right so that both the email message and attachment sent properly, but I got it working. The code of my solution was fairly specific to the application, so I’ve modified it to make it more generically applicable for this post. The (untested but generic) variant of the solution looks like: