Home > php > Send e-mails from PHP via Gmail using Swift Mailer [PHP]

Send e-mails from PHP via Gmail using Swift Mailer [PHP]

Problem

You have a PHP script from which you want to send e-mails. You want an easy solution, and it’d be nice to send the e-mails via a Gmail account.

Solution

There are several ways to send e-mails from PHP. A sophisticated (and easy) solution is using Swift Mailer, which is an open-source library for sending e-mails from PHP 5 applications. See the docs here.

For my application I created a dedicated Gmail account, I refer to this as me@gmail.com. I put Swift Mailer in the following directory: ~/public_html/Swift. Here is the PHP code:

setUsername('me@gmail.com')
  ->setPassword('pass');

$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('Wonderful Subject')
  ->setFrom(array('me@gmail.com' => 'MY NAME'))
  ->setTo(array('to@destination.com' => 'YOU'))
  ->setBody('This is the text of the mail sent by Swift using SMTP transport.');
//$attachment = Swift_Attachment::newInstance(file_get_contents('path/logo.png'), 'logo.png');
//$message->attach($attachment);
$numSent = $mailer->send($message);
printf("Sent %d message(s)\n", $numSent);
?>

Credits

This post is based on this thread.

Links
Some related links, I didn’t test them:

Advertisements
Categories: php Tags: , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: