phpmailer发送邮件_使用PHPMailer用PHP发送电子邮件

phpmailer发送邮件

PHPMailer is perhaps the most popular open-source PHP library to send emails with. It was first released way back in 2001, and since then it has become a PHP developer’s favorite way of sending emails programmatically, aside from a few other fan favorites like Swiftmailer.

PHPMailer可能是最受欢迎的用于发送电子邮件的开源PHP库。 它于2001年首次发布,此后,它成为PHP开发人员最喜欢的以编程方式发送电子邮件的方法,除了其他一些喜欢的邮件(Swiftmailer)

In this article, we’ll talk about why you should use PHPMailer instead of PHP’s mail() function, and we’ll show some code samples on how to use this library.

在本文中,我们将讨论为什么应该使用PHPMailer而不是PHP的mail()函数,并且还将展示一些有关如何使用该库的代码示例。

This popular article was updated in 2020 to offer the most up-to-date instructions for working with PHPMailer.

这篇热门文章在2020年进行了更新,以提供有关使用PHPMailer的最新说明。

它是PHP的mail()函数的替代方法吗? (Is It an Alternative to PHP’s mail() Function?)

In most cases, it’s an alternative to PHP’s mail() function, but there are many other cases where the mail() function is simply not flexible enough to achieve what you need.

在大多数情况下,它是PHP的mail()函数的替代方法,但是在许多其他情况下, mail()函数根本不够灵活,无法实现所需的功能。

First of all, PHPMailer provides an object-oriented interface, whereas mail() is not object oriented. PHP developers generally hate to create $headers strings while sending emails using the mail() function because they require a lot of escaping. PHPMailer makes this a breeze. Developers also need to write dirty code (escaping characters, encoding and formatting) to send attachments and HTML based emails when using the mail() function, whereas PHPMailer makes this painless.

首先,PHPMailer提供了一个面向对象的接口,而mail()不是面向对象的。 PHP开发人员通常讨厌在使用mail()函数发送电子邮件时创建$headers字符串,因为它们需要大量转义。 PHPMailer使这变得轻而易举。 开发人员还需要编写肮脏的代码(转义字符,编码和格式),以便在使用mail()函数时发送附件和基于HTML的电子邮件,而PHPMailer则使此工作变得轻而易举。

Also, the mail() function requires a local mail server to send out emails, which is not always trivial to set up. PHPMailer can use a non-local mail server (SMTP) if you have authentication.

此外, mail()函数需要本地邮件服务器发送电子邮件,这并不总是很容易设置的。 如果您具有身份验证,PHPMailer可以使用非本地邮件服务器(SMTP)。

Further advantages include:

其他优点包括:

  • It can print various kinds of error messages in more than 40 languages when it fails to send an email.

    如果无法发送电子邮件,它可以使用40多种语言打印各种错误消息。
  • It has integrated SMTP protocol support and authentication over SSL and TLS.

    它具有集成的SMTP协议支持以及基于SSL和TLS的身份验证。
  • It can send an alternative plain-text version of email for non-HTML email clients.

    它可以为非HTML电子邮件客户端发送电子邮件的替代纯文本版本。
  • It has a very active developer community that keeps it secure and up to date.

    它有一个非常活跃的开发人员社区,可确保其安全性和最新性。

PHPMailer is also used by popular PHP content management systems like WordPress, Drupal, and Joomla.

流行PHP内容管理系统(如WordPress,Drupal和Joomla)也使用PHPMailer。

安装PHPMailer (Installing PHPMailer)

You can install PHPMailer using Composer:

您可以使用Composer安装PHPMailer

composer require phpmailer/phpmailer

使用PHPMailer从本地Web服务器发送电子邮件 (Sending Email from a Local Web Server Using PHPMailer)

Here’s the simplest example of sending an email from a local web server using PHPMailer:

这是使用PHPMailer从本地Web服务器发送电子邮件的最简单示例:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require_once "vendor/autoload.php";

//PHPMailer Object
$mail = new PHPMailer(true); //Argument true in constructor enables exceptions

//From email address and name
$mail->From = "from@yourdomain.com";
$mail->FromName = "Full Name";

//To address and name
$mail->addAddress("recepient1@example.com", "Recepient Name");
$mail->addAddress("recepient1@example.com"); //Recipient name is optional

//Address to which recipient will reply
$mail->addReplyTo("reply@yourdomain.com", "Reply");

//CC and BCC
$mail->addCC("cc@example.com");
$mail->addBCC("bcc@example.com");

//Send HTML or Plain Text email
$mail->isHTML(true);

$mail->Subject = "Subject Text";
$mail->Body = "<i>Mail body in HTML</i>";
$mail->AltBody = "This is the plain text version of the email content";

try {
    $mail->send();
    echo "Message has been sent successfully";
} catch (Exception $e) {
    echo "Mailer Error: " . $mail->ErrorInfo;
}

The code and comments should be sufficiently clear to explain everything that’s going on.

代码和注释应该足够清楚,以解释正在发生的一切。

发送带有附件的电子邮件 (Sending an Email with Attachments)

Here’s an example of how to send an email with attachments using PHPMailer:

这是一个如何使用PHPMailer发送带有附件的电子邮件的示例:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require_once "vendor/autoload.php";

$mail = new PHPMailer;

$mail->From = "from@yourdomain.com";
$mail->FromName = "Full Name";

$mail->addAddress("recipient1@example.com", "Recipient Name");

//Provide file path and name of the attachments
$mail->addAttachment("file.txt", "File.txt");        
$mail->addAttachment("images/profile.png"); //Filename is optional

$mail->isHTML(true);

$mail->Subject = "Subject Text";
$mail->Body = "<i>Mail body in HTML</i>";
$mail->AltBody = "This is the plain text version of the email content";

try {
    $mail->send();
    echo "Message has been sent successfully";
} catch (Exception $e) {
    echo "Mailer Error: " . $mail->ErrorInfo;
}

Here, we’re attaching two files — file.txt, which resides in the same directory as the script, and images/profile.png, which resides in images directory of the script directory.

在这里,我们将附加两个文件file.txtimages/profile.png ,该文件与脚本位于同一目录,而images/profile.png则位于脚本目录的images目录中。

To add attachments to the email, we just need to call the function addAttachment of the PHPMailer object by passing the file path as argument. For attaching multiple files, we need to call it multiple times.

要将附件添加到电子邮件中,我们只需要通过传递文件路径作为参数来调用PHPMailer对象的addAttachment函数。 要附加多个文件,我们需要多次调用它。

故障排除 (Troubleshooting)

In our two examples, we used PHPMailer’s Exception class for debugging, so any errors thrown will help us debug any issues that may occur. We also added the argument true to PHPMailer constructor, to output higher-level, more descriptive exceptions.

在我们的两个示例中,我们使用PHPMailer的Exception类进行调试,因此抛出的任何错误将有助于我们调试可能发生的任何问题。 我们还为PHPMailer构造函数添加了true参数,以输出更高级别,更具描述性的异常。

Depending on the system we use, probably the most frequent error we’ll see will be related to running the mail() function in the background:

根据我们使用的系统,我们可能会看到的最常见的错误可能与在后台运行mail()函数有关:

Mailer Error: Could not instantiate mail function.

Mailer错误:无法实例化邮件功能。

If we need more details on the error, we can also add something like this to the catch clause:

如果我们需要有关错误的更多详细信息,我们还可以在catch子句中添加以下内容:

print_r(error_get_last());

Usually, the problem with the mail function will be related to the missing mail server setup, in which case the error_get_last function will return something like this:

通常,邮件功能的问题与缺少的邮件服务器设置有关,在这种情况下, error_get_last函数将返回如下内容:

Array (
    [type] => 2
    [message] => mail(): Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()
    [file] => OUR_PATH \vendor\phpmailer\phpmailer\src\PHPMailer.php
    [line] => 863
)

This is the issue we’ll probably encounter most frequently, and we can solve it easily by using SMTP.

这是我们可能最常遇到的问题,我们可以使用SMTP轻松解决它。

显示本地化的错误消息 (Displaying Localized Error Messages)

$mail->ErrorInfo can return error messages in 43 different languages.

$mail->ErrorInfo可以返回43种不同语言的错误消息。

To display error messages in a different language, copy the language directory from PHPMailer’s source code to the project directory.

要以另一种语言显示错误消息,请将language目录从PHPMailer的源代码复制到项目目录。

To return error messages in Russian, for example, set the PHPMailer object to the Russian language using the below method call:

例如,要以俄语返回错误消息,请使用以下方法调用将PHPMailer对象设置为俄语:

$mail->setLanguage("ru");

You can also add your own language files to the language directory.

您也可以将自己的语言文件添加到language目录。

使用SMTP (Using SMTP)

You can use the mail server of an another host to send email, but for this you first need to have authentication. For example, to send an email from Gmail’s mail server, you need to have a Gmail account.

您可以使用其他主机的邮件服务器发送电子邮件,但是为此,您首先需要进行身份验证。 例如,要从Gmail的邮件服务器发送电子邮件,您需要具有一个Gmail帐户。

SMTP is a protocol used by mail clients to send an email send request to a mail server. Once the mail server verifies the email, it sends it to the destination mail server.

SMTP是邮件客户端用来将电子邮件发送请求发送到邮件服务器的协议。 邮件服务器验证电子邮件后,会将其发送到目标邮件服务器。

Here’s an example of sending an email from Gmail’s mail server from your domain. You don’t need a local mail server to run the code. We’ll be using the SMTP protocol:

这是从您的域的Gmail邮件服务器发送电子邮件的示例。 您不需要本地邮件服务器即可运行代码。 我们将使用SMTP协议:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require_once "vendor/autoload.php";

$mail = new PHPMailer(true);

//Enable SMTP debugging.
$mail->SMTPDebug = 3;                               
//Set PHPMailer to use SMTP.
$mail->isSMTP();            
//Set SMTP host name                          
$mail->Host = "smtp.gmail.com";
//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;                          
//Provide username and password     
$mail->Username = "name@gmail.com";                 
$mail->Password = "super_secret_password";                           
//If SMTP requires TLS encryption then set it
$mail->SMTPSecure = "tls";                           
//Set TCP port to connect to
$mail->Port = 587;                                   

$mail->From = "name@gmail.com";
$mail->FromName = "Full Name";

$mail->addAddress("name@example.com", "Recepient Name");

$mail->isHTML(true);

$mail->Subject = "Subject Text";
$mail->Body = "<i>Mail body in HTML</i>";
$mail->AltBody = "This is the plain text version of the email content";

try {
    $mail->send();
    echo "Message has been sent successfully";
} catch (Exception $e) {
    echo "Mailer Error: " . $mail->ErrorInfo;
}

Gmail requires TLS encryption over SMTP, so we set it accordingly. Before you send via SMTP, you need to find out the host name, port number, encryption type if required and if authentication is required you also need the username and password. Note that having two-factor authentication enabled on Gmail won’t let you use their SMTP with username/password. Instead, additional configuration will be required.

Gmail需要通过SMTP进行TLS加密,因此我们进行了相应的设置。 通过SMTP发送之前,需要找出主机名,端口号,加密类型(如果需要),如果需要身份验证,则还需要用户名和密码。 请注意,在Gmail上启用了双重身份验证后,您将无法通过用户名/密码使用其SMTP。 相反,将需要其他配置

One big advantage in using remote SMTP over local mail is that if you use PHP’s mail() function to send email with the from address domain set to anything other than the local domain name (name of the server), then the recipient’s email server’s attack filters will mark it as spam. For example, if you send an email from a server with actual host name example.com with the from address name@gmail.com to name@yahoo.com, then Yahoo’s servers will mark it as spam or display a message to the user not to trust the email because the mail’s origin is example.com and yet it presents itself as if coming from gmail.com. Although you own name@gmail.com, there’s no way for Yahoo to find that out.

在使用远程SMTP在本地邮件的一大好处是,如果你使用PHP的mail()函数来发送电子邮件from地址域设置为本地域名(服务器名),则收件人的邮件服务器的攻击其他任何过滤器会将其标记为垃圾邮件。 例如,如果你从实际的主机名称的服务器发送电子邮件example.comfrom地址name@gmail.comname@yahoo.com ,那么雅虎的服务器将其标记为垃圾邮件或显示一条消息给用户不之所以信任电子邮件,是因为该邮件的来源是example.com ,但其自身却好像来自gmail.com 。 尽管您拥有name@gmail.com ,但Yahoo无法找到name@gmail.com

使用POP3检索电子邮件 (Retrieving Emails using POP3)

PHPMailer also allows POP-before-SMTP verification to send emails. In other words, you can authenticate using POP and send email using SMTP. Sadly, PHPMailer doesn’t support retrieving emails from mail servers using the POP3 protocol. It’s limited to only sending emails.

PHPMailer还允许SMTP之前的POP验证发送电子邮件。 换句话说,您可以使用POP进行身份验证并使用SMTP发送电子邮件。 遗憾的是,PHPMailer不支持使用POP3协议从邮件服务器检索电子邮件。 仅限于发送电子邮件。

结论 (Conclusion)

If you’re a PHP developer, there’s little chance of avoiding having to send emails programmatically. While you may opt for third-party services like Mandrill or SendGrid, sometimes that just isn’t an option, and rolling your own email sending library even less so. That’s where PHPMailer and its alternatives (Zend Mail, Swift Mailer, and so on) come in.

如果您是PHP开发人员,那么几乎不必避免以编程方式发送电子邮件。 尽管您可以选择使用Mandrill或SendGrid之类的第三方服务,但有时这不是一个选择,而滚动自己的电子邮件发送库的可能性甚至更低。 那就是PHPMailer及其替代品(Zend Mail,Swift Mailer等)出现的地方。

You can learn about this library’s APIs in the repository wiki, or in the official documentation.

您可以在存储库Wiki官方文档中了解此库的API。

Are you getting bogged down with PHP library dependencies? Watch our screencast and learn about how Composer can help you manage this for you.

您是否对PHP库依赖感到困惑? 观看我们的截屏视频 ,了解Composer如何帮助您进行管理。

翻译自: https://www.sitepoint.com/sending-emails-php-phpmailer/

phpmailer发送邮件

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值