php-swiftmailerHow to use Swiftmailer to send RFC 2822 compliant emails?
Swiftmailer is a popular library for sending emails in PHP. It can be used to send RFC 2822 compliant emails.
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');
// 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 a new SMTP transport instance.->setUsername('yourusername')
and->setPassword('yourpassword')
: These lines set the username and password for the SMTP server.$mailer = Swift_Mailer::newInstance($transport)
: This line creates a new mailer instance using the transport instance.$message = Swift_Message::newInstance('Wonderful Subject')
: This line creates a new message instance.->setFrom(array('[email protected]' => 'John Doe'))
and->setTo(array('[email protected]', '[email protected]' => 'A name'))
: These lines set the sender and recipient of the message.->setBody('Here is the message itself')
: This line sets the body of the message.$result = $mailer->send($message)
: This line sends the message.
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 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...