提供发送电子邮件是典型的 PHP 驱动的 Web 应用程序通常需要的功能之一。您希望通过 PHP 应用程序本身而不是其他邮件服务向注册用户发送包含通知、更新和其他通信的电子邮件。您可以通过采用本章中描述的技术将此功能添加到您的 PHP 应用程序中。
PHP 有一个内置的 mail() 函数来发送电子邮件。但是,您需要正确配置 “php.ini” 设置才能执行此操作。首先,您必须知道您正在使用的 Web 托管平台的 SMTP 域。例如,如果您的网站托管在 GoDaddy 托管服务上,则 SMTP 域为“smtp.secureserver.net”,您应该在配置中使用该域。
如果您使用基于 Windows 的 GoDaddy 托管,则应确保在 php.ini 文件中启用了两个指令。第一个称为 SMTP,用于定义您的电子邮件服务器地址。第二个称为 sendmail_from,定义您自己的电子邮件地址。
Windows 的配置应如下所示 -
; For Win32 only.
SMTP = smtp.secureserver.net
; For win32 only
sendmail_from = webmaster@qikepu.com
Linux 用户只需让 PHP 知道他们的 sendmail 应用程序的位置。path 和任何所需的交换都应该指定给 sendmail_path 指令。
Linux 的配置应如下所示 -
; 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 );
参数
设置为 −
参数 | 描述 |
---|---|
to | 必需。指定电子邮件的收件人 |
subject | 必需。指定电子邮件的主题。此参数不能包含任何换行符 |
message | 必需。定义要发送的消息。每行应用 LF (\n) 分隔。行数不应超过 70 个字符 |
headers | 可选。指定其他标题,如 From、Cc 和 Bcc。其他标头应使用 CRLF (\r\n) 分隔 |
parameters | 可选。指定发送邮件程序的附加参数 |
可以将多个收件人指定为逗号分隔列表中 mail() 函数的第一个参数。
发送 HTML 电子邮件
当您使用 PHP 发送短信时,所有内容都将被视为简单文本。即使您将在文本消息中包含 HTML 标签,它也会显示为简单文本,并且 HTML 标签不会根据 HTML 语法进行格式化。
但是 PHP 提供了将 HTML 消息作为实际 HTML 消息发送的选项。
发送电子邮件时,您可以指定 Mime 版本、内容类型和字符集以发送 HTML 电子邮件。
例子
以下示例显示了如何将 HTML 电子邮件消息发送到“xyz@qikepu.com”,并将其复制到“afgh@qikepu.com”。您可以以这样一种方式编写此程序,使其应接收来自用户的所有内容,然后应发送电子邮件。
它应该接收来自用户的所有内容,然后应该发送电子邮件。
<?php
$to = "xyz@qikepu.com";
$subject = "这是主题";
$message = "<b>这是HTML消息。</b>";
$message .= "<h1>这是标题。</h1>";
$header = "From:abc@qikepu.com \r\n";
$header .= "Cc:afgh@qikepu.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 "消息发送成功...";
}else {
echo "无法发送消息...";
}
?>
它将产生以下输出 -
sh: 1: /usr/sbin/sendmail: not found
从 Localhost 发送电子邮件
上述调用 PHP mail 的方法可能不适用于您的本地主机。在这种情况下,还有发送电子邮件的替代解决方案。您可以使用 PHPMailer 通过 SMTP 从 localhost 发送电子邮件。
PHPMailer 是一个开源库,用于连接 SMTP 以发送电子邮件。您可以从 PEAR 或 Composer 存储库下载它,也可以从 https://github.com/PHPMailer/PHPMailer 下载它。从此处下载 ZIP 文件,将 PHPMailer 文件夹的内容复制到 PHP 配置中指定的 include_path 目录之一,然后手动加载每个类文件。
例子
使用以下 PHP 脚本通过 PHPMailer 库发送电子邮件 -
Phpmailer.php
<?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'])){
// 获取 POST 价值
$fname=$_POST['fname'];
$toemail=$_POST['toemail'];
$subject=$_POST['subject'];
$message=$_POST['message'];
$mail->isSMTP(); // 将邮件程序设置为使用SMTP
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'myID@gmail.com'; // SMTP用户名
$mail->Password = 'mypassword'; // SMTP密码
// 启用TLS加密,也接受“ssl”
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom(myID@gmail.com', 'My_Name');
$mail->addReplyTo(myID@gmail.com', 'My_Name');
$mail->addAddress($toemail); // 添加收件人
$mail->isHTML(true); // 将电子邮件格式设置为HTML
$bodyContent=$message;
$mail->Subject =$subject;
$body = 'Dear'.$fname;
$body .='<p>'.$message.'</p>';
$mail->Body = $body;
if(!$mail->send()) {
echo '无法发送消息.';
echo '邮件错误: ' . $mail->ErrorInfo;
} else {
echo '消息已发送';
}
}
?>
使用以下 HTML 表单编写邮件消息。表单将提交到上述 phpmail.php 脚本
Email.html
<h1>PHP-发送电子邮件</h1>
<form action="PHPmailer.php" method="post">
<label for="inputName">姓名</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">主题</label>
<input type="text" id="inputSubject" name="subject" required>
<label for="inputMessage">信息</label>
<textarea id="inputMessage" name="message" rows="5" required></textarea>
<button type="submit" name="send">发送</button>
</form>
通过电子邮件发送附件
要发送包含混合内容的电子邮件,您应该将 Content-type 标头设置为 multipart/mixed。然后,可以在边界内指定文本和附件部分。
边界以两个连字符开头,后跟一个唯一编号,该编号不能显示在电子邮件的消息部分中。PHP 函数 md5 用于创建一个 32 位十六进制数以创建唯一数字。表示电子邮件最后一部分的最后一个边界也必须以两个连字符结尾。
请看下面的例子 -
<?php
// 请求变量
$from = $_REQUEST["from"];
$emaila = $_REQUEST["emaila"];
$filea = $_REQUEST["filea"];
if ($filea) {
function mail_attachment ($from , $to, $subject, $message, $attachment){
$fileatt = $attachment; // 文件路径
$fileatt_type = "application/octet-stream"; // 文件类型
$start = strrpos($attachment, '/') == -1 ?
strrpos($attachment, '//') : strrpos($attachment, '/')+1;
// 将作为附件用于文件的文件名
$fileatt_name = substr($attachment, $start,
strlen($attachment));
$email_from = $from; // 电子邮件来自那里?
$subject = "New Attachment Message";
$email_subject = $subject; // 电子邮件的主题
$email_txt = $message; // 电子邮件中包含的消息
$email_to = $to; // 电子邮件发给谁?
$headers = "From: ".$email_from;
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);
$msg_txt="\n\n 您收到了来自 $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 .= "这是MIME格式的多部分消息。\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.";
// 在附件发送后删除文件。
unlink($attachment);
} else {
die("很抱歉,无法发送电子邮件。请返回并重试!");
}
}
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 = "正在附加文件。。。请稍候";
}
}
}
</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">你的姓名:</td>
</tr>
<tr>
<td><input name = "from" type = "text" id = "from" size = "30"></td>
</tr>
<tr valign = "bottom">
<td height = "20">你的邮件地址:</td>
</tr>
<tr>
<td class = "frmtxt2"><input name = "emaila" type = "text" id = "emaila" size = "30"></td>
</tr>
<tr>
<td height = "20" valign = "bottom">添加文件:</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>
它将产生以下输出 -