Skip to content

Instantly share code, notes, and snippets.

@lesstif
Last active August 4, 2020 01:18
Show Gist options
  • Save lesstif/79ed4c8e39fcffdcbf055d91fa14d433 to your computer and use it in GitHub Desktop.
Save lesstif/79ed4c8e39fcffdcbf055d91fa14d433 to your computer and use it in GitHub Desktop.
Send email using PHP Swift mailer
<?php
require_once '/path/to/vendor/autoload.php';
$host = env('MAIL_HOST');
$user = env('MAIL_USERNAME');
$port = env('MAIL_PORT');
$password = env('MAIL_PASSWORD');
$security = env('MAIL_ENCRYPTION');
// Create the Transport
$transport = (new Swift_SmtpTransport($host, $port, $security))
->setUsername($user)
->setPassword($password)
;
// Create the Mailer using your created Transport
$mailer = new Swift_Mailer($transport);
// mail content body
$body = '<b>Hello</b> Here is the message itself';
// Create attachment
$attach1 = Swift_Attachment::fromPath('screen_shot.jpg');
// create attachement 2
$content = file_get_contents('./storage/uploads/sample.pdf');
$attach2 = new Swift_Attachment($content, 'attachment-file-name.pdf');
// Create a message
$message = (new Swift_Message('Wonderful Subject'))
->setFrom(['noreply@example.org' => 'John Doe'])
->setReplyTo('reply@example.org', 'Reply To')
->setTo(['receiver@domain.org', 'other@domain.org' => 'A name'])
->setBody($body, 'text/html')
->attach($attach1)
->attach($attach2)
;
// Send the message
$result = $mailer->send($message);
// result is The number of successful recipients. Can be 0 which indicates failure
if ($result === 0) {
die("error occured!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment