How can PHP libraries like PHPMailer be utilized for sending emails with attachments?
To send emails with attachments using PHP libraries like PHPMailer, you can simply add the attachment file to the email message before sending it. PHPMailer provides a method called `addAttachment()` which allows you to attach files to your email.
<?php
require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'yourpassword';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->isHTML(true);
$mail->Subject = 'Email with Attachment';
$mail->Body = 'This is a test email with attachment.';
// Attach file
$file_path = 'path/to/attachment.pdf';
$mail->addAttachment($file_path);
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
?>
Related Questions
- What are the advantages and disadvantages of using PHP for handling Multicast streams compared to learning C specifically for this purpose?
- How can one ensure that PHP code is properly executed on a server, especially when encountering issues like only seeing the source code of the PHP file?
- What are some potential pitfalls of resizing images in PHP, as discussed in the forum thread?