How to send email using the GMail SMTP server from a PHP page?

Spread the love

Sometimes, we want to send email using the GMail SMTP server from a PHP page.

In this article, we’ll look at how to send email using the GMail SMTP server from a PHP page.

How to send email using the GMail SMTP server from a PHP page?

To send email using the GMail SMTP server from a PHP page, we can use the Swift mailer library.

We install it by running

composer require "swiftmailer/swiftmailer:^6.0"

Then, we write

require_once '/path/to/vendor/autoload.php';

$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, "ssl")
  ->setUsername('GMAIL_USERNAME')
  ->setPassword('GMAIL_PASSWORD');

$mailer = Swift_Mailer::newInstance($transport);

$message = Swift_Message::newInstance('Test Subject')
  ->setFrom(array('abc@example.com' => 'ABC'))
  ->setTo(array('xyz@test.com'))
  ->setBody('This is a test mail.');

$result = $mailer->send($message);

to create a SmtpTransport instance with

$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, "ssl")

Then we use setUsername and setPassword to set the GMail username and password.

Next, we create the $mailer object to let us set the $message.

We create the $message with the from, to, and body fields with

$message = Swift_Message::newInstance('Test Subject')
  ->setFrom(array('abc@example.com' => 'ABC'))
  ->setTo(array('xyz@test.com'))
  ->setBody('This is a test mail.');

Finally, we send the email with

$result = $mailer->send($message);

and get the result from $result.

Conclusion

To send email using the GMail SMTP server from a PHP page, we can use the Swift mailer library.

Leave a Reply

Your email address will not be published. Required fields are marked *