phpmailerHow do I use PHPMailer to send an email with an attachment?
Using PHPMailer to send an email with an attachment is a fairly straightforward process.
First, include the PHPMailer library:
require 'PHPMailerAutoload.php';
Then, create an instance of the PHPMailer class and set the necessary options:
$mail = new PHPMailer;
$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]', 'Recipient Name');
$mail->Subject = 'PHPMailer Attachment';
$mail->Body = 'This is an automated message.';
Next, add the attachment to the message:
$mail->addAttachment('/path/to/file.pdf');
Finally, send the message and check for errors:
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
Output example
Message sent!
Code explanation
require 'PHPMailerAutoload.php'
: This line includes the PHPMailer library.$mail = new PHPMailer;
: This line creates an instance of the PHPMailer class.$mail->setFrom('[email protected]', 'Your Name');
: This sets the sender's address and name.$mail->addAddress('[email protected]', 'Recipient Name');
: This sets the recipient's address and name.$mail->Subject = 'PHPMailer Attachment';
: This sets the subject of the email.$mail->Body = 'This is an automated message.';
: This sets the body of the email.$mail->addAttachment('/path/to/file.pdf');
: This adds an attachment to the message.if (!$mail->send()) {
: This checks if the message was sent successfully.echo "Mailer Error: " . $mail->ErrorInfo;
: This prints the error message if an error occurred.echo "Message sent!";
: This prints a success message if the message was sent successfully.
Helpful links
More of Phpmailer
- How can I configure PHPMailer to support Polish characters?
- How can I use PHPMailer in Yii 1?
- How can I configure PHPMailer to work with GoDaddy?
- How can I set up PHPMailer to use Zimbra SMTP?
- How can I use PHPMailer without SMTP secure?
- How do I determine which version of PHPMailer I'm using?
- How can I use PHPMailer to send emails with a Yahoo account?
- How do I use PHPMailer to attach a ZIP file?
- How can I send emails using PHPMailer without using SMTP?
- How do I update PHPMailer?
See more codes...