php-swiftmailerHow to set up Swiftmailer with Gmail SMTP?
Swiftmailer is a popular library for sending emails from PHP applications. Setting up Swiftmailer with Gmail SMTP is easy and straightforward.
// Create the Transport
$transport = (new Swift_SmtpTransport('smtp.gmail.com', 465, 'ssl'))
->setUsername('[email protected]')
->setPassword('yourpassword');
// Create the Mailer using your created Transport
$mailer = new Swift_Mailer($transport);
// Create a message
$message = (new Swift_Message('Wonderful Subject'))
->setFrom(['[email protected]' => 'John Doe'])
->setTo(['[email protected]', '[email protected]' => 'A name'])
->setBody('Here is the message itself');
// Send the message
$result = $mailer->send($message);
The output of the example code is $result
which is an integer representing the number of successful recipients.
Code explanation
-
$transport
: This is the transport object which is used to connect to the Gmail SMTP server. It requires the hostname, port and encryption type as parameters. -
$mailer
: This is the mailer object which is used to send the message. It requires the transport object as a parameter. -
$message
: This is the message object which is used to create the email. It requires the from, to, subject and body as parameters. -
$result
: This is the result of the send operation which is an integer representing the number of successful recipients.
Helpful links
More of Php Swiftmailer
- How to set timeout with Swiftmailer?
- How to use SMTP with Swiftmailer?
- How to use TLS 1.2 with Swiftmailer?
- How to get the response code when using Swiftmailer?
- How to use Swiftmailer to send RFC 2822 compliant emails?
- How to configure Swiftmailer for Postfix?
- How to send emails in UTF8 using Swiftmailer?
- How to send emails to multiple recipients with Swiftmailer?
- How to set the port for Swiftmailer?
- How to enable TLS with Swiftmailer?
See more codes...