PHP

php如何发送带附件的邮件

小樊
81
2024-09-24 11:36:10
栏目: 编程语言

要使用PHP发送带附件的电子邮件,您可以使用PHPMailer库。以下是使用PHPMailer发送带附件的电子邮件的步骤:

  1. 首先,确保您已经安装了PHPMailer库。如果没有,可以通过Composer安装:
composer require phpmailer/phpmailer
  1. 创建一个新的PHP文件(例如:send_email_with_attachment.php),并在其中包含以下代码:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    // 邮件服务器设置
    $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      // 开启详细调试输出
    $mail->isSMTP();                                            // 设置邮件发送使用SMTP协议
    $mail->Host       = 'smtp.example.com';                     // 设置邮件发送服务器的地址
    $mail->SMTPAuth   = true;                                   // 开启使用SMTP认证功能
    $mail->Username   = 'your_email@example.com';               // 设置发送邮件的用户名
    $mail->Password   = 'your_email_password';               // 设置发送邮件的密码
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            // 设置加密类型
    $mail->Port       = 465;                                    // 设置邮件发送端口

    // 发件人和收件人
    $mail->setFrom('your_email@example.com', 'Your Name');
    $mail->addAddress('recipient@example.com', 'Recipient Name');

    // 附件
    $mail->addAttachment('/path/to/your/attachment.ext', 'Attachment Name');

    // 邮件内容
    $mail->isHTML(true);                                        // 设置邮件正文格式为HTML
    $mail->Subject = 'Email with Attachment';                   // 设置邮件主题
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
?>
  1. 修改代码中的以下变量:
  1. 在命令行中运行PHP文件:
php send_email_with_attachment.php

现在,您应该能够成功发送带有附件的电子邮件。如果您遇到任何问题,请检查您的邮件服务器设置和电子邮件凭据是否正确。

0
看了该问题的人还看了