php-swiftmailerHow to send HTML emails with Swiftmailer?
Swiftmailer is a popular library for sending HTML emails in PHP. It is easy to use and provides a lot of flexibility.
Example code
<?php
// Require the Swift Mailer library
require_once 'lib/swift_required.php';
// Create the Transport
$transport = Swift_SmtpTransport::newInstance('smtp.example.org', 25)
->setUsername('yourusername')
->setPassword('yourpassword');
// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
// Create a message
$message = Swift_Message::newInstance('Wonderful Subject')
->setFrom(array('[email protected]' => 'John Doe'))
->setTo(array('[email protected]', '[email protected]' => 'A name'))
->setBody('Here is the message itself')
->addPart('<q>Here is the message itself</q>', 'text/html');
// Send the message
$result = $mailer->send($message);
Output example
int(1)
Code explanation
require_once 'lib/swift_required.php';- This line requires the Swift Mailer library.$transport = Swift_SmtpTransport::newInstance('smtp.example.org', 25)- This line creates the transport using the SMTP server and port.->setUsername('yourusername')- This line sets the username for the SMTP server.->setPassword('yourpassword')- This line sets the password for the SMTP server.$mailer = Swift_Mailer::newInstance($transport);- This line creates the mailer using the created transport.$message = Swift_Message::newInstance('Wonderful Subject')- This line creates a message with the given subject.->setFrom(array('[email protected]' => 'John Doe'))- This line sets the sender of the message.->setTo(array('[email protected]', '[email protected]' => 'A name'))- This line sets the recipient of the message.->setBody('Here is the message itself')- This line sets the plain text body of the message.->addPart('<q>Here is the message itself</q>', 'text/html')- This line adds an HTML part to the message.$result = $mailer->send($message);- This line sends the message.
Helpful links
More of Php Swiftmailer
- How to use SMTP with Swiftmailer?
- How to use TLS 1.2 with Swiftmailer?
- How to set timeout with Swiftmailer?
- How to send emails without encryption in SwiftMailer?
- How to send emails to multiple recipients with Swiftmailer?
- How to set the reply to address in Swiftmailer?
- Swiftmailer usage example
- How to use Swiftmailer to send RFC 2822 compliant emails?
- How to access Swiftmailer logs?
- How to ignore a certificate when using Swiftmailer?
See more codes...