Quick Reference for Sending a Message
Sending a message is very straightforward. You create a Transport, use it to create the Mailer, then you use the Mailer to send the message.
To send a Message:
- Create a Transport from one of the provided Transports – Swift_SmtpTransport, Swift_SendmailTransport, Swift_MailTransport or one of the aggregate Transports.
- Create an instance of the Swift_Mailer class, using the Transport as it's constructor parameter.
- Create a Message according to the instructions laid out in Creating Messages
- Send the message via the send() or the batchSend() methods on the Mailer object.
When using send() the message will be sent just like it would be sent if you used your mail client. An integer is returned which includes the number of successful recipients. If none of the recipients could be sent to then zero will be returned, which equates to a boolean false. If you set two To: recipients and three Bcc: recipients in the message and all of the recipients are delivered to successfully then the value 5 will be returned.
batchSend() returns a number just like send(), except that it does not include all of the To: recipients in the Headers. Each recipient is sent a unique copy of the message with only their address in the headers. This is advised for newsletter systems.
Sending a Message
<?php
require_once 'lib/swift_required.php';
//Create the Transport
$transport = Swift_SmtpTransport::newInstance('smtp.example.org', 25)
->setUsername('your username')
->setPassword('your password')
;
/*
You could alternatively use a different transport such as Sendmail or Mail:
//Sendmail
$transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs');
//Mail
$transport = Swift_MailTransport::newInstance();
*/
//Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
//Create a message
$message = Swift_Message::newInstance('Wonderful Subject')
->setFrom(array('john@doe.com' => 'John Doe'))
->setTo(array('receiver@domain.org', 'other@domain.org' => 'A name'))
->setBody('Here is the message itself')
;
//Send the message
$result = $mailer->send($message);
/*
You can alternatively use batchSend() to send the message
$result = $mailer->batchSend($message);
*/