Php 简明教程
PHP - Sending Emails
发送电子邮件是 PHP 提供支持的典型 Web 应用程序的常见需求功能之一。你会希望通过 PHP 应用程序本身(而非不同的邮件服务)向你的注册用户发送包含通知、更新和其他通信的电子邮件。你可以通过采用本章中描述的技术向你的 PHP 应用程序添加此功能。
The provision of sending emails is one the commonly required features of a typical PHP powered web application. You would like to send emails containing notifications, updates and other communications to your registered users, through your PHP application itself, instead of a different mail service. You can add this capability to your PHP application by adopting the techniques described in this chapter.
PHP 内置有一个 mail() 函数,可用于发送电子邮件。但是,你需要正确配置“php.ini”设置,才能使用它。首先,你必须知道你正在使用的网络托管平台的 SMTP 域名。例如,如果你的网站托管在 GoDaddy 托管服务上,则 SMTP 域名是“smtp.secureserver.net”,你应该在配置中使用它。
PHP has a built-in mail() function to send an email. However, you need configure properly the "php.ini" settings to be able to do so. First, you must know the SMTP domain of the web hosting platform that you are using. For example, if your website is being hosted on GoDaddy hosting service, the SMTP domain is "smtp.secureserver.net", which you should use in the configuration.
如果你使用 GoDaddy 的基于 Windows 的托管,你应该确保在 php.ini 文件中启用了两个指令。第一个指令称为 SMTP,它定义你的电子邮件服务器地址。第二个指令称为 sendmail_from,它定义你的自己电子邮件地址。
If you use Windows based hosting of GoDaddy, you should ensure that two directives are enabled in php.ini file. The first is called SMTP that defines your email server address. The second is called sendmail_from which defines your own email address.
用于 Windows 的配置看起来应该像这样:
The configuration for Windows should look something like this −
[mail function]
; For Win32 only.
SMTP = smtp.secureserver.net
; For win32 only
sendmail_from = webmaster@tutorialspoint.com
Linux 用户只需让 PHP 知道其 sendmail 应用程序的位置即可。应将路径和任何所需的 switch 指定给 sendmail_path 指令。
Linux users simply need to let PHP know the location of their sendmail application. The path and any desired switches should be specified to the sendmail_path directive.
用于 Linux 的配置看起来应该像这样:
The configuration for Linux should look something like this −
[mail function]
; For Win32 only.
SMTP =
; For win32 only
sendmail_from =
; For Unix only
sendmail_path = /usr/sbin/sendmail -t -i
PHP 中的 mail() 函数需要三个强制性参数,这些参数指定收件人的电子邮件地址、邮件主题和实际邮件,此外还有另外两个可选参数。
mail() function in PHP requires three mandatory arguments that specify the recipient’s email address, the subject of the message and the actual message additionally there are other two optional parameters.
mail( to, subject, message, headers, parameters );
Parameters
-
to − Required. Specifies the receiver / receivers of the email
-
subject − Required. Specifies the subject of the email. This parameter cannot contain any newline characters
-
message − Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters
-
headers − Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n)
-
parameters − Optional. Specifies an additional parameter to the send mail program
多个收件人可指定为 mail() 函数的第一个参数,用逗号分隔。
Multiple recipients can be specified as the first argument to the mail() function in a comma separated list.
Sending HTML Email
当你使用 PHP 发送文本消息时,所有内容都将被视为纯文本。即使你将 HTML 标记包含在文本消息中,它也将显示为纯文本,并且 HTML 标记不会根据 HTML 语法进行格式化。但 PHP 提供了将 HTML 邮件作为实际 HTML 邮件发送的选项。
When you send a text message using PHP then all the content will be treated as simple text. Even if you will include HTML tags in a text message, it will be displayed as simple text and HTML tags will not be formatted according to HTML syntax. But PHP provides option to send an HTML message as actual HTML message.
发送邮件时,你可以指定一个 Mime 版本、内容类型和字符集来发送 HTML 邮件。
While sending an email message you can specify a Mime version, content type and character set to send an HTML email.
Example
以下示例显示了如何将 HTML 邮件发送至“ xyz@somedomain.com ”,并抄送给“ afgh@somedomain.com ”。你可以以这样的方式编写此程序,使其接收来自用户的全部内容,然后发送电子邮件。
The following example shows how to send an HTML email message to "xyz@somedomain.com" copying it to "afgh@somedomain.com". You can code this program in such a way that it should receive all content from the user and then it should send an email.
它应当接收来自用户的全部内容,然后发送一封电子邮件。
It should receive all content from the user and then it should send an email.
<?php
$to = "xyz@somedomain.com";
$subject = "This is subject";
$message = "<b>This is HTML message.</b>";
$message .= "<h1>This is headline.</h1>";
$header = "From:abc@somedomain.com \r\n";
$header .= "Cc:afgh@somedomain.com \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$retval = mail ($to,$subject,$message,$header);
if( $retval == true ) {
echo "Message sent successfully...";
}else {
echo "Message could not be sent...";
}
?>
它将生成以下 output −
It will produce the following output −
Message could not be sent...
sh: 1: /usr/sbin/sendmail: not found
Sending Email from Localhost
上面的 PHP mail() 调用方法可能无法在你的 localhost 上运行。在这种情况中,有一种替代方案可用于发送电子邮件。你可以使用 PHPMailer 从 localhost 使用 SMTP 发送电子邮件。
The above method of calling PHP mail() may not work on your localhost. In that case, there is an alternate solution to sending email. You can use PHPMailer to send email using SMTP from localhost.
PHPMailer 是一个开源库,用于连接 SMTP 来发送电子邮件。你可以从 PEAR 或 Composer 存储库下载它,或从 https://github.com/PHPMailer/PHPMailer 下载它。从这里下载 ZIP 文件,并将 PHPMailer 文件夹的内容复制到 PHP 配置中指定的某个 include_path 目录中,并手动加载每个类文件。
PHPMailer is an open-source library to connect SMTP to send emails. You can download it from PEAR or Composer repositories, or download it from https://github.com/PHPMailer/PHPMailer. Download the ZIP file from here, and copy the contents of the PHPMailer folder into one of the include_path directories specified in your PHP configuration and load each class file manually.
Example
使用以下 PHP 脚本通过 PHPMailer 库发送电子邮件:
Use the following PHP script to send email with PHPMailer library −
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require_once __DIR__ . '/vendor/phpmailer/src/Exception.php';
require_once __DIR__ . '/vendor/phpmailer/src/PHPMailer.php';
require_once __DIR__ . '/vendor/phpmailer/src/SMTP.php';
require 'vendor/autoload.php';
$mail = new PHPMailer;
if(isset($_POST['send'])){
// getting post values
$fname=$_POST['fname'];
$toemail=$_POST['toemail'];
$subject=$_POST['subject'];
$message=$_POST['message'];
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'myID@gmail.com'; // SMTP username
$mail->Password = 'mypassword'; // SMTP password
// Enable TLS encryption, 'ssl' also accepted
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom(myID@gmail.com', 'My_Name');
$mail->addReplyTo(myID@gmail.com', 'My_Name');
$mail->addAddress($toemail); // Add a recipient
$mail->isHTML(true); // Set email format to HTML
$bodyContent=$message;
$mail->Subject =$subject;
$body = 'Dear'.$fname;
$body .='<p>'.$message.'</p>';
$mail->Body = $body;
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
}
?>
使用以下 HTML 表单编写邮件消息。表单提交给上述 phpmail.php 脚本
Use the following HTML form to compose the mail message. The form is submitted to the above phpmail.php script
<h1>PHP - Sending Email</h1>
<form action="PHPmailer.php" method="post">
<label for="inputName">Name</label>
<input type="text" id="inputName" name="fname" required>
<label for="inputEmail">Email</label>
<input type="email" id="inputEmail" name="toemail" required>
<label for="inputSubject">Subject</label>
<input type="text" id="inputSubject" name="subject" required>
<label for="inputMessage">Message</label>
<textarea id="inputMessage" name="message" rows="5" required></textarea>
<button type="submit" name="send">Send</button>
</form>
Sending Attachments with Email
要发送具有混合内容的电子邮件,您应将 Content-type 头设为 multipart/mixed。然后,可以在边界中指定文本和附件部分。
To send an email with mixed content you should set Content-type header to multipart/mixed. Then text and attachment sections can be specified within boundaries.
一个边界以两个连字符开始,后跟一个唯一数字,该数字不能出现在电子邮件的消息部分中。PHP 函数 md5() 用于创建一个 32 位十六进制数以创建唯一数字。表示电子邮件最终部分的最终边界也必须以两个连字符结束。
A boundary is started with two hyphens followed by a unique number which can not appear in the message part of the email. A PHP function md5() is used to create a 32 digit hexadecimal number to create unique number. A final boundary denoting the email’s final section must also end with two hyphens.
Example
请看以下示例:
Take a look at the following example −
<?php
// request variables
$from = $_REQUEST["from"];
$emaila = $_REQUEST["emaila"];
$filea = $_REQUEST["filea"];
if ($filea) {
function mail_attachment ($from , $to, $subject, $message, $attachment){
$fileatt = $attachment; // Path to the file
$fileatt_type = "application/octet-stream"; // File Type
$start = strrpos($attachment, '/') == -1 ?
strrpos($attachment, '//') : strrpos($attachment, '/')+1;
// Filename that will be used for the file as the attachment
$fileatt_name = substr($attachment, $start,
strlen($attachment));
$email_from = $from; // Who the email is from
$subject = "New Attachment Message";
$email_subject = $subject; // The Subject of the email
$email_txt = $message; // Message that the email has in it
$email_to = $to; // Who the email is to
$headers = "From: ".$email_from;
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);
$msg_txt="\n\n You have recieved a new attachment message from $from";
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . "
boundary=\"{$mime_boundary}\"";
$email_txt .= $msg_txt;
$email_message .= "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" . "Content-Type:text/html;
charset = \"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" .
$email_txt . "\n\n";
$data = chunk_split(base64_encode($data));
$email_message .= "--{$mime_boundary}\n" . "Content-Type: {$fileatt_type};\n" .
" name = \"{$fileatt_name}\"\n" . //"Content-Disposition: attachment;\n" .
//" filename = \"{$fileatt_name}\"\n" . "Content-Transfer-Encoding:
"base64\n\n" . $data . "\n\n" . "--{$mime_boundary}--\n";
$ok = mail($email_to, $email_subject, $email_message, $headers);
if($ok) {
echo "File Sent Successfully.";
// delete a file after attachment sent.
unlink($attachment);
} else {
die("Sorry but the email could not be sent. Please go back and try again!");
}
}
move_uploaded_file($_FILES["filea"]["tmp_name"],
'temp/'.basename($_FILES['filea']['name']));
mail_attachment("$from", "youremailaddress@gmail.com",
"subject", "message", ("temp/".$_FILES["filea"]["name"]));
}
?>
<html>
<head>
<script language = "javascript" type = "text/javascript">
function CheckData45() {
with(document.filepost) {
if(filea.value ! = "") {
document.getElementById('one').innerText = "Attaching File ... Please Wait";
}
}
}
</script>
</head>
<body>
<table width = "100%" height = "100%" border = "0"
cellpadding = "0" cellspacing = "0">
<tr>
<td align = "center">
<form name = "filepost" method = "post"
action = "file.php" enctype = "multipart/form-data" id = "file">
<table width = "300" border = "0" cellspacing = "0"
cellpadding = "0">
<tr valign = "bottom">
<td height = "20">Your Name:</td>
</tr>
<tr>
<td><input name = "from" type = "text" id = "from" size = "30"></td>
</tr>
<tr valign = "bottom">
<td height = "20">Your Email Address:</td>
</tr>
<tr>
<td class = "frmtxt2"><input name = "emaila" type = "text" id = "emaila" size = "30"></td>
</tr>
<tr>
<td height = "20" valign = "bottom">Attach File:</td>
</tr>
<tr valign = "bottom">
<td valign = "bottom"><input name = "filea" type = "file" id = "filea" size = "16"></td>
</tr>
<tr>
<td height = "40" valign = "middle">
<input name = "Reset2" type = "reset" id = "Reset2" value = "Reset">
<input name = "Submit2" type = "submit" value = "Submit" onClick = "return CheckData45()">
</td>
</tr>
</table>
</form>
<center>
<table width = "400">
<tr>
<td id = "one"></td>
</tr>
</table>
</center>
</td>
</tr>
</table>
</body>
</html>
它将生成以下 output −
It will produce the following output −