PHPphp

文章

使用PHPMailer发送邮箱

时间:2024-12-14 14:48 阅读:1126

1.首先使用composer安装扩展库

composer require phpmailer/phpmailer

2.以qq邮箱为例,在设置中开启服务,获取授权码

3.发送邮件

<?php
//引入类库
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

$mail = new PHPMailer(true);
try {
    //Server settings
    $mail->SMTPDebug = 0;                      // debug SMTP::DEBUG_SERVER
    $mail->isSMTP();
    $mail->Host       = 'smtp.126.com';                    // 邮件服务器地址
    $mail->SMTPAuth   = true;
    $mail->Username   = '';                     // 邮箱地址账户
    $mail->Password   = '';                     // 授权码
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
    $mail->Port       = 465;                                    // 端口
    //Recipients
    $mail->setFrom('');//发件人邮箱
    $mail->addAddress('');     // 收件人邮箱
    $mail->addAttachment('test.csv');         // 可添加附件
    // Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = '标题';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';//邮件内容,可发送验证码和通知,支持html
    $mail->send();
    echo 'success';
} catch (Exception $e) {
    echo "error";
}

4.还可以发送带图片的邮件

<?php
$img = 'shing.jpg';
$img_data = base64_encode(file_get_contents($img));
$to = '@qq.com';
$title = '图片测试';
$message = "<img src='data:image/jpeg;base64,".$img_data."'/>";//echo $message;exit;
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
// Additional headers
$headers .= 'To: Mary <mary@example.com>, Kelly <kelly@example.com>' . "\r\n";
$headers .= 'From: Birthday Reminder <birthday@example.com>' . "\r\n";
$headers .= 'Cc: birthdayarchive@example.com' . "\r\n";
$headers .= 'Bcc: birthdaycheck@example.com' . "\r\n";
mail($to,$title,$message,$headers);
?>


Copyright © 2024  Erbing 版权所有  备案号:黑ICP备17006126号-3

0.969009s