php发送电子邮件_使用PHP发送电子邮件

php发送电子邮件

We know why you’re here… you want to write a script to send emails to your friends with funny return addresses. I’m here to tell you you’re better than that. There’s so much more you could be doing with your life! But, what other reasons could you possibly have?

我们知道您为什么在这里……您想编写一个脚本,用有趣的寄信人地址向您的朋友发送电子邮件。 我在这里告诉你你比那更好。 您可以为自己的生活做更多的事情! 但是,您可能还有其他原因吗?

Well, maybe you have a cron job that you want to inform you of issues, have a user-initiated script you’d like to be notified when run, have a “Contact Us” form that forwards messages to you, want to flex your PHP muscles and write your own web-based mail client, need to set up a confirmation-by-email script – there are plenty of other reasons to send email with PHP. Plus, it’s so easy!

好吧,也许您有一个计划任务要通知您问题,有一个您希望在运行时收到通知的用户启动脚本,有一个“联系我们”表格可以将消息转发给您,您想展示您的信息PHP实力雄厚,并编写了自己的基于Web的邮件客户端,需要设置“通过电子邮件确认”脚本–使用PHP发送电子邮件还有很多其他原因。 另外,它是如此简单!

In most cases your installation of PHP will be capable of sending emails. If you are using a shared host, or if you installed PHP using a package management system like apt-get, more than likely you’re all set. You’ll really only need to worry about extra configuration if you’re compiling PHP from source or if you’re running it on Windows. In either case, there are plenty of resources available online to help you out. Because that’s all beyond the scope of this article, I’ll assume you’re set. If not, Google will be your friend.

在大多数情况下,您PHP安装将能够发送电子邮件。 如果您使用共享主机,或者使用apt-get之类的程序包管理系统安装了PHP,则可能已经准备就绪。 如果要从源代码编译PHP或在Windows上运行PHP,则实际上只需要担心额外的配置。 无论哪种情况,都有大量在线资源可为您提供帮助。 因为这超出了本文的范围,所以我假设您已设置好。 否则,Google将成为您的朋友。

超级基础的例子 (The Super-Basic Example)

To send just a really simple email, the code is:

要发送非常简单的电子邮件,代码是:

<?php
mail($address, $subject, $message);

Really, that’s all there is to sending basic plain-text emails (if it doesn’t work for you, again check with Google to see how to configure PHP correctly).

真的,这就是发送基本的纯文本电子邮件的全部功能(如果它对您不起作用,请再次与Google联系,以了解如何正确配置PHP)。

Now let’s see how this would look in a script. Let’s say, for example, you want the script to email you every time a query fails:

现在,让我们看一下脚本中的外观。 例如,假设您希望脚本在每次查询失败时通过电子邮件发送给您:

<?php
$query = "SELECT left_arm AS arm_in, right_leg AS leg_in, front_head AS head_in FROM hokey_pokey WHERE its_about = 'all'";
try {
    $result = $db->query($query);
    // ...
}
catch (PDOException $e) {
    mail("bad_things@my_database.com", "Error in " . $_SERVER["SCRIPT_NAME"], $e->getMessage());
}

If there’s some unforeseen error that happens with the execution of your query then you’ll get an email informing you what script had an error and what that error was.

如果执行查询时发生一些无法预料的错误,那么您将收到一封电子邮件,通知您哪个脚本有错误以及该错误是什么。

完整HTML邮件示例 (A Full-Blown HTML Mail Example)

Now, let’s check out a full-blown multipart mail() example that has an HTML body with a plain text alternative and a file attachment:

现在,让我们看一个完整的multipart mail()示例,该示例具有HTML正文,纯文本替代形式和文件附件:

<?php
$emailList = array("first_sucker@wazoo.com",
                   "nextSucker@hemail.com",
                   "othersucker32@clotmail.com",
                   "sckrfnl@mayohell.com");

$headers = "From: "Fluffy Mumsy" <sincere@dumsing.com>rn" .
   "Reply-To: weregonnaberich@shhhsecret.comrn" .
   "MIME-Version: 1.0rn" .
   "Content-Type: multipart/mixed; boundary="YaGottaKeepEmSeparated"rn";
$subject = "Please donate all your moneys to us";
$goodAttachment = chunk_split(base64_encode(file_get_contents( "novyrus.zip")));
$body = "--YaGottaKeepEmSeparatedrn" .
    "Content-Type: multipart/alternative; boundary="EachEmailAlternative"rn" .
     "--EachEmailAlternativern" .
      "Content-Type: text/plain; charset="iso-8859-1"rn" .
      "Content-Transfer-Encoding: 7bitrn" .
      "You have cheap text email you have no money. Please ignore.rn" .
     "--EachEmailAlternativern" .
      "Content-Type: text/html; charset="iso-8859-1"rn" .
       "<html>
 <head>
  <title>We need money to give you</title>
 </head>
 <body>
  <p>We found some <span style='color:green'>money</span>. And we need you give us money to give some you. We is good people. You can trust. Please install contact information attachment</p>
 </body>
</html>rn" .
    "--YaGottaKeepEmSeparatedrn" .
     "Content-Type: application/zip; name="novyrus.zip"rn" .
     "Content-Transfer-Encoding: base64rn" .
     "Content-Disposition: attachmentrn" .
     $goodAttachment . "rn" .
    "--YaGottaKeepEmSeparated--";

foreach ($emailList AS $addy) {
   $success = mail($addy, $subject, $body, $headers);
   if (!$success) {
       echo "Mail to " . $addy . " is fail.";
   }
}

Certain aspects of more typical email scripts had been simplified to make the general concept easier to grasp, though I will touch on those in this breakdown.

尽管我将在本细分中涉及的那些内容,但已简化了更典型的电子邮件脚本的某些方面,以使总体概念更易于掌握。

First, the $emailList array is populated with some email addresses I’d like to share my message with. The array is iterated through at the end of the script and each address will be sent a copy of my email.

首先, $emailList数组填充了一些我想与之共享消息的电子邮件地址。 在脚本末尾遍历该数组,每个地址将被发送一份我的电子邮件副本。

Next, the $headers string is built with various mail headers. Each header in the string is separated with a CRLF (rn) per RFC 2822, the standard that defines the format of email messages.

接下来,用各种邮件头构建$headers字符串。 根据RFC 2822 (定义电子邮件消息格式的标准),字符串中的每个标头都用CRLF( rn )分隔。

"From: "Fluffy Mumsy" <sincere@dumsing.com>rn" The From header specifies the email address the recipient will see the message as having come from.

"From: "Fluffy Mumsy" <sincere@dumsing.com>rn"发件人标头指定收件人将看到邮件来自的电子邮件地址。

"Reply-To: weregonnaberich@shhhsecret.comrn" The Reply-To header is the email address to which an email reply should be sent. By making it different than the “From:” header, the chances of this email being identified as spam increases (though if this were the only thing that caused an email client to raise a red flag this message is spam then it would probably get through).

"Reply-To: weregonnaberich@shhhsecret.comrn"回复至标头是应将电子邮件回复发送到的电子邮件地址。 通过使其与“发件人:”标头不同,此电子邮件被识别为垃圾邮件的机会增加了(尽管如果这是唯一导致电子邮件客户端发出危险信号的东西,则该邮件是垃圾邮件,那么它很可能会通过)。

"MIME-Version: 1.0rn" The MIME-Version header tells the server to expect Multipurpose Internet Mail Extensions in the body, which allows you to have a more advanced email than simple text.

"MIME-Version: 1.0rn" MIME版本标头告诉服务器,该邮件正文中包含多用途Internet邮件扩展 ,它使您可以拥有比简单文本更高级的电子邮件。

"Content-Type: multipart/mixed; boundary="YaGottaKeepEmSeparated"rn" The “Content-Type” header actually does two things: it indicates that there will be multiple parts in the body of various kinds, and it specifies what string is used to divide each part. This boundary string needs cannot appear anywhere else in the email or the mail client will not be able to parse the message correctly. You could use “12” as your boundary for example, though chances are that it will show up elsewhere in the message. I chose “YaGottaKeepEmSeparated”. Most people assign a randomly generated hash to serve as the boundary, like $boundary = md5(time()), since the chance of collision is very low.

"Content-Type: multipart/mixed; boundary="YaGottaKeepEmSeparated"rn" “ Content-Type”标头实际上做了两件事:它表明主体中将有多个部分,并且指定了要使用的字符串划分每个部分。 此边界字符串需求不能出现在电子邮件中的其他任何地方,否则邮件客户端将无法正确解析消息。 例如,您可以使用“ 12”作为边界,尽管很有可能它会出现在消息的其他位置。 我选择“ YaGottaKeepEmSeparated”。 大多数人都会分配一个随机生成的哈希作为边界,例如$boundary = md5(time()) ,因为发生冲突的机会非常低。

The contents of novyrus.zip, which here happens to be located in the same directory as the script, is base64-encoded and broken into “chunks” for easier digestion by the mail client. The result is stored in $goodAttachment which will make an appearance later.

novyrus.zip的内容与脚本位于同一目录,它的内容novyrus.zip base64编码,并分成“块”,以便邮件客户端更容易地进行消化。 结果存储在$goodAttachment ,稍后会出现。

Finally, the body of the email message is composed…

最后,电子邮件的正文组成了……

"--YaGottaKeepEmSeparatedrn" This is the first instance of using the boundary defined earlier and says to the mail client, “hey, here’s the start of the first section of the email message.”, and it always starts with the double-dash in front of your chosen boundary string.

"--YaGottaKeepEmSeparatedrn"这是使用先前定义的边界的第一个实例,并对邮件客户端说:“嘿,这是电子邮件第一部分的开始。”,它总是以双破折号开头您选择的边界字符串的前面。

"Content-Type: multipart/alternative; boundary="EachEmailAlternative"rn" Besides “multipart/mixed” given in the email’s headers, you can also use a Content-Type header with “multipart/alternative” within the body and with a different boundary specific to this breakdown to provide alternate formats for the message.

"Content-Type: multipart/alternative; boundary="EachEmailAlternative"rn"除了电子邮件标题中提供的“ multipart / mixed”外,您还可以在正文中使用Content-Type标题,其中“ multipart / alternative”与其他标题不同特定于此细分的边界,以提供消息的备用格式。

"--EachEmailAlternativern" This is the first instance of the nested boundary and starts the first alternate version of the message.

"--EachEmailAlternativern"这是嵌套边界的第一个实例,并启动消息的第一个备用版本。

"Content-Type: text/plain; charset="iso-8859-1"rn" This Content-Type header tells the mail client this alternative is plain text. If the client isn’t capable of displaying more complex formats, such as HTML, then it will use this version of the message.

"Content-Type: text/plain; charset="iso-8859-1"rn"此Content-Type标头告诉邮件客户端此替代方法是纯文本。 如果客户端无法显示更复杂的格式(例如HTML),则它将使用此版本的消息。

"Content-Transfer-Encoding: 7bitrn" The Content-Transfer-Encoding header specifies the encoding scheme used in the message. For historical reasons, “7bit” is the default value and so this could be omitted. I included it so just so you’ll be aware of it.

"Content-Transfer-Encoding: 7bitrn" Content-Transfer-Encoding标头指定了消息中使用的编码方案。 由于历史原因,“ 7bit”是默认值,因此可以省略。 我包括了它,以便您可以意识到它。

"You have cheap text email you have no money. Please ignore.rn" This is the text-only version of the message which people using non-HTML-capable readers will see.

"You have cheap text email you have no money. Please ignore.rn"这是使用不支持HTML的阅读器的人们看到的纯文本版本。

"--EachEmailAlternativern" The end of the first alternative has been reached, and you’re ready to start the next alternate version.

"--EachEmailAlternativern"第一个替代方法的结尾已到,您已经准备好开始下一个替代版本。

"Content-Type: text/html; charset="iso-8859-1"rn" This Content-Type header informs the client this version is formatted as HTML, and the set of characters that is used.

"Content-Type: text/html; charset="iso-8859-1"rn"此Content-Type标头通知客户端此版本的格式为HTML,以及所使用的字符集。

"<html> ... </html>rn" Notice that this version, besides the inclusion of HTML tags, has content that is considerably different than the plain text version. Some spam filters may view this as one more reason to block me message from getting to the inbox.

"<html> ... </html>rn"请注意,此版本除了包含HTML标记外,其内容也与纯文本版本大不相同。 一些垃圾邮件过滤器可能将此视为阻止我发送邮件到收件箱的另一个原因。

"--YaGottaKeepEmSeparatedrn" This is the multipart/mixed boundary, indicating that you’ve reached the end of the message body section with all its alternatives.

"--YaGottaKeepEmSeparatedrn"这是一个多部分/混合边界,表示您已到达消息正文部分的结尾,并选择了所有替代方法。

"Content-Type: application/zip; name="novyrus.zip"rn" The Content-Type header signals the next part of the email is an attachment (the novyrus.zip file), and that it is ZIP file.

"Content-Type: application/zip; name="novyrus.zip"rn" Content-Type标头表示电子邮件的下一部分是附件( novyrus.zip文件),并且是ZIP文件。

"Content-Transfer-Encoding: base64rn" 7bit encoding restricts characters to seven bits and might not be able to faithfully represent all the necessary binary characters for the ZIP file, which was why the file was base64-encoded and chunked. The Content-Transfer-Encoding header here lets the client know how to decode the attachment file.

"Content-Transfer-Encoding: base64rn" 7位编码将字符限制为7位,并且可能无法如实地表示ZIP文件的所有必需二进制字符,这就是为什么文件经过base64编码和分块的原因。 此处的Content-Transfer-Encoding标头使客户端知道如何解码附件文件。

"Content-Disposition: attachmentrn" The Content-Disposition header details how content should be presented; there are two possible values: attachment and inline. While it would hardly make sense to display a ZIP file inline element in a message, it comes in handy to embed images.

"Content-Disposition: attachmentrn" Content-Disposition标头详细说明了内容应如何显示; 有两个可能的值: attachinline 。 虽然在邮件中显示ZIP文件内联元素几乎没有任何意义,但嵌入图像非常方便。

$goodAttachment . "rn" The contents of the attached file is simply dumped into the mix.

$goodAttachment . "rn" $goodAttachment . "rn"附加文件的内容只是转储到混合文件中。

"--YaGottaKeepEmSeparated--" This is the final boundary declaring that nothing more shall follow by ending with one last set of double-dashes.

"--YaGottaKeepEmSeparated--"这是最后一个边界,它声明不再需要以最后一组双破折号结尾。

摘要 (Summary)

There you have it! You’ve seen how to send super-basic text email message, and full-fledge HTML emails with attachments. Simple emails are just a matter of calling the mail() function. For HTML messages, you need to break your email into segments using the MIME standards, divided by a boundary of your choosing. Then, you define what the content is, how it’s encoded, possibly the disposition, and then the content itself. Depending to whom you plan on sending emails, you will want to be conscientious about factors that may cause your message to be more likely flagged as spam, just in case you want to actually want to send something serious.

你有它! 您已经了解了如何发送超基本文本电子邮件以及带有附件的完整HTML电子邮件。 简单的电子邮件只需调用mail()函数即可。 对于HTML消息,您需要使用MIME标准将电子邮件分为多个部分,然后将其除以您选择的边界。 然后,您定义内容是什么,如何编码,可能的处置方式以及内容本身。 根据您打算向谁发送电子邮件,您会谨慎对待可能导致您的邮件更可能被标记为垃圾邮件的因素,以防万一您确实想发送严重的邮件。

Image via Photosani / Shutterstock

图片来自Photosani / Shutterstock

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

php发送电子邮件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值