PHP对邮件的操作处理可能大部分开发者都已经了解,但是对于邮件处理在PHP中到底有几种方式可能只有一个模糊的概念,今天我们针对PHP发送邮件的技术做一次详细的解析,以供大家学习和交流
https://github.com/PHPMailer/PHPMailer/
下载PHPMailer,PHPMailer 可能需要 PHP 的 sockets 扩展支持,而有的SMTP服务器还强制使用SSL加密链接,如:QQ邮箱,那就还需要包含 openssl 扩展。可以使用 phpinfo() 函数查看当前PHP环境是否开启了 socket 和 openssl 扩展模块,如下图所示:composer
方式:require __DIR__.'/PHPMailer/Exception.php'; require __DIR__.'/PHPMailer/PHPMailer.php'; require __DIR__.'/PHPMailer/SMTP.php'; use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; use PHPMailer\PHPMailer\Exception; // Instantiation and passing `true` enables exceptions $mail = new PHPMailer(true); try { //smtp 服务配置 $mail->SMTPDebug = SMTP::DEBUG_SERVER; //打开调试 $mail->isSMTP(); // 使用smtp发送 $mail->Host = 'smtp.163.com'; // smtp 服务器地址,我使用的是163的,所以设置为smtp.163.com $mail->SMTPAuth = true; // 是否进行smtp账号认证 $mail->Username = 'user@example.com'; // SMTP 用户名 $mail->Password = 'secret'; // SMTP 登录密码 $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // 使用的数据传输安全协议 $mail->Port = 25; // SMTP服务器的端口号,一般为25,安全连接为465 //接收人配置 $mail->setFrom('from@example.com', 'Mailer'); $mail->addAddress('joe@example.net', 'Joe User'); // 添加接收人 $mail->addAddress('ellen@example.com'); // 添加一个名称缺省的接收人 $mail->addReplyTo('info@example.com', 'Information'); $mail->addCC('cc@example.com'); $mail->addBCC('bcc@example.com'); // Attachments $mail->addAttachment('/var/tmp/file.tar.gz'); // 添加一个附件 $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}"; }