php5.5使用PHPMailer-5.2发送邮件的完整步骤

yipeiwu_com5年前PHP代码库

前言

这几天一直被邮件发送功能搞得头大,作为一个小白,遇到坑总是难免的。今天终于把phpmailer搞定了,下面就来总结一下

PHPMailer - A full-featured email creation and transfer class for PHP。

在PHP环境中可以使用PHPMailer来创建和发送邮件。

最新版本(20181012)是PHPMailer 6.0.5,这个无法兼容php5.5以下的环境。由于我需要维护php5.3的项目,需要切换到PHPMailer5.2来发送邮件。

下载地址: https://github.com/PHPMailer/PHPMailer/releases/tag/v5.2.24

下面话不多说了,来一起看看详细的介绍吧

基本使用

下载解压后。新建一个测试demo。

<?php
require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

$mail->SMTPDebug = 3;        // Enable verbose debug output

$mail->isSMTP();          // Set mailer to use SMTP
$mail->Host = 'smtp.exmail.qq.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true;        // Enable SMTP authentication
$mail->Username = 'xxx@qq.com';     // SMTP username
$mail->Password = 'yourpassword';       // SMTP password
$mail->SMTPSecure = 'ssl';       // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465;         // TCP port to connect to

$mail->setFrom('fromWho@qq.com', 'Mailer');
$mail->addAddress('toWhom@qq.com', 'Ryan Miao');  // Add a recipient
$mail->addAddress('ellen@example.com');    // Name is optional
// $mail->addReplyTo('info@example.com', 'Information');
$mail->addCC('cc@example.com');
$mail->addBCC('bcc@example.com');

$mail->addAttachment('/var/tmp/file.tar.gz');   // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$mail->isHTML(true);         // Set email format to 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';

if(!$mail->send()) {
 echo 'Message could not be sent.';
 echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
 echo 'Message has been sent';
}

开启SMTPDebug可以查看日志

 `0` No output
 `1` Commands
 `2` Data and commands
 `3` As 2 plus connection status
 `4` Low-level data output

错误信息保存在 $mail->ErrorInfo对象中。

保存为mail.php, 命令行执行

php mail.php

即可看到日志,以及邮件发送成功。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对【宜配屋www.yipeiwu.com】的支持。

相关文章

解析PHP中的file_get_contents获取远程页面乱码的问题

PHP的file_get_contents获取远程页面内容,如果是gzip编码过的,返回的字符串就是编码后的乱码1、解决方法,找个ungzip的函数来转换下2、给你的url加个前缀,这样...

php使用GD实现颜色渐变实例

php使用GD实现颜色渐变实例

本文实例讲述了php使用GD实现颜色渐变的方法。分享给大家供大家参考。具体实现方法如下: <?php $im = imagecreate(255, 255); $bg...

PHP版本如何选择?应该使用哪个版本?

PHP版本如何选择?应该使用哪个版本?

超过75%的网站使用了PHP作为开发语言,wordpress,phpmyadmin和其他一些开源项目的盛行,带来了一大批的长尾用户。然而,他们一般安装之后却很少升级。下图是目前PHP的使...

PHP __autoload()方法真的影响性能吗?

PHP __autoload()方法真的影响性能吗?

介绍 对于php性能问题,议论最多的就是__autoload()方法,很多人提到这个方法非常影响性能。还有人说opcode也能影响到__autoload()方法,所以针对这两点我做了个测...

PHP 基于Yii框架中使用smarty模板的方法详解

第一种方法按照YII系统的办法生成视图觉得有点麻烦,觉得用smarty更省事。尝试着把smarty模板加进来了。复制代码 代码如下:date_default_timezone_set("...