一、注意事项
1. 推荐用户使用 PHPMailer 包:
·如果是新项目并且使用 composer 那么只需在 composer.json 加上 "phpmailer/phpmailer": "^6.5" ,或者执行 composer require phpmailer/phpmailer ,然后使用下面的代码即可。
·如果是老项目且没有使用 composer 的,需手动引入 PHPMailer。
3. 服务地址和端口请参见 SMTP 服务地址。
以下是代码示例:
<?phpuse PHPMailer\\PHPMailer\\PHPMailer;use PHPMailer\\PHPMailer\\SMTP;use PHPMailer\\PHPMailer\\Exception;require './PHPMailer/src/Exception.php';require './PHPMailer/src/PHPMailer.php';require './PHPMailer/src/SMTP.php';$mail = new PHPMailer(true);try { //Server settings $mail->SMTPDebug = SMTP::DEBUG_SERVER; //启用详细的调试输出 $mail->SMTPAuth = true; //启用SMTP身份验证 //$mail->AuthType = 'LOGIN'; $mail->isSMTP(); //使用SMTP发送邮件 $mail->Host = 'smtp.qcloudmail.com'; //设置SMTP服务器地址 $mail->Username = 'abc@qq.aa.com'; //控制台配置的发信地址 $mail->Password = '123456'; //控制台设置的发信地址密码 $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; //启用隐式TLS加密 $mail->CharSet = PHPMailer::CHARSET_UTF8; $mail->CharSet = 'UTF-8'; $mail->ContentType = 'text/plain; charset=UTF-8'; $mail->Encoding = PHPMailer::ENCODING_BASE64; //$mail->Encoding = '8bit'; $mail->Port = 465; //设置TCP连接端口 //Recipients $mail->setFrom('abc@qq.aa.com', 'fromName'); $mail->addAddress('test@test.com', 'toName'); //添加收件人 //$mail->addAddress('ellen@example.com'); //$mail->addReplyTo('info@example.com', 'Information'); //$mail->addCC('cc@example.com'); //(可选)添加抄送 //$mail->addBCC('bcc@example.com'); //(可选)添加密送 //Attachments $mail->addAttachment('./tmp.txt'); //添加附件 //$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); //(可选)添加附件并指定名称 //Content //$mail->isHTML(true); //(可选)设置邮件格式为HTML $mail->Subject = 'Here is the subject'; $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}";}