Php 简明教程
PHP - Sending Emails
发送电子邮件是 PHP 提供支持的典型 Web 应用程序的常见需求功能之一。你会希望通过 PHP 应用程序本身(而非不同的邮件服务)向你的注册用户发送包含通知、更新和其他通信的电子邮件。你可以通过采用本章中描述的技术向你的 PHP 应用程序添加此功能。
PHP 内置有一个 mail() 函数,可用于发送电子邮件。但是,你需要正确配置“php.ini”设置,才能使用它。首先,你必须知道你正在使用的网络托管平台的 SMTP 域名。例如,如果你的网站托管在 GoDaddy 托管服务上,则 SMTP 域名是“smtp.secureserver.net”,你应该在配置中使用它。
如果你使用 GoDaddy 的基于 Windows 的托管,你应该确保在 php.ini 文件中启用了两个指令。第一个指令称为 SMTP,它定义你的电子邮件服务器地址。第二个指令称为 sendmail_from,它定义你的自己电子邮件地址。
用于 Windows 的配置看起来应该像这样:
[mail function]
; For Win32 only.
SMTP = smtp.secureserver.net
; For win32 only
sendmail_from = webmaster@tutorialspoint.com
Linux 用户只需让 PHP 知道其 sendmail 应用程序的位置即可。应将路径和任何所需的 switch 指定给 sendmail_path 指令。
用于 Linux 的配置看起来应该像这样:
[mail function]
; For Win32 only.
SMTP =
; For win32 only
sendmail_from =
; For Unix only
sendmail_path = /usr/sbin/sendmail -t -i
PHP 中的 mail() 函数需要三个强制性参数,这些参数指定收件人的电子邮件地址、邮件主题和实际邮件,此外还有另外两个可选参数。
mail( to, subject, message, headers, parameters );
Parameters
-
to − 必需。指定电子邮件的接收者/收件人
-
subject − 必需。指定电子邮件的主题。此参数不能包含任何换行符
-
message − 必需。定义要发送的邮件。每一行都应该用 LF (\n) 分隔。行数不得超过 70 个字符
-
headers − 可选。指定其他标头,例如发件人、抄送和密件抄送。应该用 CRLF (\r\n) 分隔其他标头
-
parameters − 可选。指定发送邮件程序的其他参数
多个收件人可指定为 mail() 函数的第一个参数,用逗号分隔。
Sending HTML Email
当你使用 PHP 发送文本消息时,所有内容都将被视为纯文本。即使你将 HTML 标记包含在文本消息中,它也将显示为纯文本,并且 HTML 标记不会根据 HTML 语法进行格式化。但 PHP 提供了将 HTML 邮件作为实际 HTML 邮件发送的选项。
发送邮件时,你可以指定一个 Mime 版本、内容类型和字符集来发送 HTML 邮件。
Example
以下示例显示了如何将 HTML 邮件发送至“ xyz@somedomain.com ”,并抄送给“ afgh@somedomain.com ”。你可以以这样的方式编写此程序,使其接收来自用户的全部内容,然后发送电子邮件。
它应当接收来自用户的全部内容,然后发送一封电子邮件。
<?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 −
Message could not be sent...
sh: 1: /usr/sbin/sendmail: not found
Sending Email from Localhost
上面的 PHP mail() 调用方法可能无法在你的 localhost 上运行。在这种情况中,有一种替代方案可用于发送电子邮件。你可以使用 PHPMailer 从 localhost 使用 SMTP 发送电子邮件。
PHPMailer 是一个开源库,用于连接 SMTP 来发送电子邮件。你可以从 PEAR 或 Composer 存储库下载它,或从 https://github.com/PHPMailer/PHPMailer 下载它。从这里下载 ZIP 文件,并将 PHPMailer 文件夹的内容复制到 PHP 配置中指定的某个 include_path 目录中,并手动加载每个类文件。
Example
使用以下 PHP 脚本通过 PHPMailer 库发送电子邮件:
<?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 脚本
<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。然后,可以在边界中指定文本和附件部分。
一个边界以两个连字符开始,后跟一个唯一数字,该数字不能出现在电子邮件的消息部分中。PHP 函数 md5() 用于创建一个 32 位十六进制数以创建唯一数字。表示电子邮件最终部分的最终边界也必须以两个连字符结束。
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 −