使用的PHPMailer版本:5.2.1
以下是PHPMailer的example文件夹里给出的:test_gamil_basic.php的部分代码。
代码如下 | 复制代码 |
$mail = new PHPMailer(); $body = file_get_contents('contents.html'); //$body = $_POST['body']; $body = eregi_replace("[]",'',$body); $mail->IsSMTP(); // telling the class to use SMTP $mail->SMTPDebug = 2; // enables SMTP debug information (for testing) // 1 = errors and messages // 2 = messages only $mail->SMTPAuth = true; // enable SMTP authentication $mail->SMTPSecure = "ssl"; // sets the prefix to the servier $mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server or ssl://smtp.gmail.com $mail->Port = 465; // set the SMTP port for the GMAIL server $mail->Username = "yourusername@gmail.com"; // GMAIL username $mail->Password = "yourpassword"; // GMAIL password $mail->SetFrom('name@yourdomain.com', 'First Last'); $mail->AddReplyTo("name@yourdomain.com","First Last"); $mail->Subject = "PHPMailer Test Subject via smtp (Gmail), basic"; $mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test $mail->MsgHTML($body); $address = "whoto@otherdomain.com"; $mail->AddAddress($address, "John Doe"); $mail->AddAttachment("images/phpmailer.gif"); // attachment $mail->AddAttachment("images/phpmailer_mini.gif"); // attachment if(!$mail->Send()) { echo "Mailer Error: " . $mail->ErrorInfo; } else { echo "Message sent!"; } |
按照这个例子给出的代码操作,我遇到了以下错误:
www.111cn.net提示您 smtp error could not connect to smtp host !
的错误提示,google了下,发现是需要开启PHP的openssl扩展:
extension=php_openssl.dll //去掉最前面的分号,重启apache或nginx服务器。
HoHo~成功发送。
imap是一款邮件交互访问的协议了,下面我来给大家介绍利用php imap模块来快速获取邮件的例子,有兴趣的朋友可参考一下。列出所有目录:
代码如下 | 复制代码 |
$host = '{imap.mail.yahoo.com:993/ssl}'; 结果: Array 重新打开指定的目录: imap_reopen($inbox, $host.'Bulk Mail'); |
windows安装imap
注意在windows中我们需要开启php.ini中的一个imap模板了,在php中找到php_imap.dll扩展然后开启,同时如果你看extensions没有关php_imap.dll需要复制一个过去。
linux中安装imap
最后完整的编译 imap 模块参数如下:
代码如下 | 复制代码 |
./configure --with-php-config=/usr/local/webserver/php/bin/php-config --with-kerberos=/usr --with-imap-ssl=/usr make make install |
当你还在纠结php内置的mail()函数不能发送邮件时,那么你现在很幸运,此时的这篇文章可以帮助到你!
php利用smtp类来发邮件真是屡试不爽,我用过很久了,基本上没出过问题。本博客后台,当博主回复留言时候,会自动给网友发一封有新回复提示的邮件也是用的本文这个方法实现的。
smtp类发送邮件的方法其实很简单,也很稳定,类是别人已经写好的了,你只需要调用就行了。几行简单的配置就能发邮件,是不是很期待的试一试呢!
email.class.php文件
代码如下 | 复制代码 |
{ /* Public Variables */ var $smtp_port; var $time_out; var $host_name; var $log_file; var $relay_host; var $debug; var $auth; var $user; var $pass; /* Private Variables */ /* Constractor */ function smtp($relay_host = "", $smtp_port = 25,$auth = false,$user,$pass) { $this->debug = FALSE; $this->smtp_port = $smtp_port; $this->relay_host = $relay_host; $this->time_out = 30; //is used in fsockopen() $this->auth = $auth;//auth $this->user = $user; $this->pass = $pass; # $this->host_name = "localhost"; //is used in HELO command $this->sock = FALSE; } /* Main Function */ function sendmail($to, $from, $subject = "", $body = "", $mailtype, $cc = "", $bcc = "", $additional_headers = "") { $mail_from = $this->get_address($this->strip_comment($from)); $body = ereg_replace("(^|(rn))(.)", "1.3", $body); $header = "MIME-Version:1.0rn"; if($mailtype=="HTML"){ $header .= "Content-Type:text/htmlrn"; } $header .= "To: ".$to."rn"; if ($cc != "") { $header .= "Cc: ".$cc."rn"; } $header .= "From: $from<".$from.">rn"; $header .= "Subject: ".$subject."rn"; $header .= $additional_headers; $header .= "Date: ".date("r")."rn"; $header .= "X-Mailer:By Redhat (PHP/".phpversion().")rn"; list($msec, $sec) = explode(" ", microtime()); $header .= "Message-ID: <".date("YmdHis", $sec).".".($msec*1000000).".".$mail_from.">rn"; $TO = explode(",", $this->strip_comment($to)); if ($cc != "") { $TO = array_merge($TO, explode(",", $this->strip_comment($cc))); } if ($bcc != "") { $TO = array_merge($TO, explode(",", $this->strip_comment($bcc))); } $sent = TRUE; foreach ($TO as $rcpt_to) { $rcpt_to = $this->get_address($rcpt_to); if (!$this->smtp_sockopen($rcpt_to)) { $this->log_write("Error: Cannot send email to ".$rcpt_to."n"); $sent = FALSE; continue; } if ($this->smtp_send($this->host_name, $mail_from, $rcpt_to, $header, $body)) { $this->log_write("E-mail has been sent to <".$rcpt_to.">n"); } else { $this->log_write("Error: Cannot send email to <".$rcpt_to.">n"); $sent = FALSE; } fclose($this->sock); $this->log_write("Disconnected from remote hostn"); } return $sent; } /* Private Functions */ function smtp_send($helo, $from, $to, $header, $body = "") { if (!$this->smtp_putcmd("HELO", $helo)) { return $this->smtp_error("sending HELO command"); } #auth if($this->auth){ if (!$this->smtp_putcmd("AUTH LOGIN", base64_encode($this->user))) { return $this->smtp_error("sending HELO command"); } if (!$this->smtp_putcmd("", base64_encode($this->pass))) { return $this->smtp_error("sending HELO command"); } } # if (!$this->smtp_putcmd("MAIL", "FROM:<".$from.">")) { return $this->smtp_error("sending MAIL FROM command"); } if (!$this->smtp_putcmd("RCPT", "TO:<".$to.">")) { return $this->smtp_error("sending RCPT TO command"); } if (!$this->smtp_putcmd("DATA")) { return $this->smtp_error("sending DATA command"); } if (!$this->smtp_message($header, $body)) { return $this->smtp_error("sending message"); } if (!$this->smtp_eom()) { return $this->smtp_error("sending <CR><LF>.<CR><LF> [EOM]"); } if (!$this->smtp_putcmd("QUIT")) { return $this->smtp_error("sending QUIT command"); } return TRUE; } function smtp_sockopen($address) { if ($this->relay_host == "") { return $this->smtp_sockopen_mx($address); } else { return $this->smtp_sockopen_relay(); } } function smtp_sockopen_relay() { $this->log_write("Trying to ".$this->relay_host.":".$this->smtp_port."n"); $this->sock = @fsockopen($this->relay_host, $this->smtp_port, $errno, $errstr, $this->time_out); if (!($this->sock && $this->smtp_ok())) { $this->log_write("Error: Cannot connenct to relay host ".$this->relay_host."n"); $this->log_write("Error: ".$errstr." (".$errno.")n"); return FALSE; } $this->log_write("Connected to relay host ".$this->relay_host."n"); return TRUE;; } function smtp_sockopen_mx($address) { $domain = ereg_replace("^.+@([^@]+)$", "1", $address); if (!@getmxrr($domain, $MXHOSTS)) { $this->log_write("Error: Cannot resolve MX "".$domain.""n"); return FALSE; } foreach ($MXHOSTS as $host) { $this->log_write("Trying to ".$host.":".$this->smtp_port."n"); $this->sock = @fsockopen($host, $this->smtp_port, $errno, $errstr, $this->time_out); if (!($this->sock && $this->smtp_ok())) { $this->log_write("Warning: Cannot connect to mx host ".$host."n"); $this->log_write("Error: ".$errstr." (".$errno.")n"); continue; } $this->log_write("Connected to mx host ".$host."n"); return TRUE; } $this->log_write("Error: Cannot connect to any mx hosts (".implode(", ", $MXHOSTS).")n"); return FALSE; } function smtp_message($header, $body) { fputs($this->sock, $header."rn".$body); $this->smtp_debug("> ".str_replace("rn", "n"."> ", $header."n> ".$body."n> ")); return TRUE; } function smtp_eom() { fputs($this->sock, "rn.rn"); $this->smtp_debug(". [EOM]n"); return $this->smtp_ok(); } function smtp_ok() { $response = str_replace("rn", "", fgets($this->sock, 512)); $this->smtp_debug($response."n"); if (!ereg("^[23]", $response)) { fputs($this->sock, "QUITrn"); fgets($this->sock, 512); $this->log_write("Error: Remote host returned "".$response.""n"); return FALSE; } return TRUE; } function smtp_putcmd($cmd, $arg = "") { if ($arg != "") { if($cmd=="") $cmd = $arg; else $cmd = $cmd." ".$arg; } fputs($this->sock, $cmd."rn"); $this->smtp_debug("> ".$cmd."n"); return $this->smtp_ok(); } function smtp_error($string) { $this->log_write("Error: Error occurred while ".$string.".n"); return FALSE; } function log_write($message) { $this->smtp_debug($message); if ($this->log_file == "") { return TRUE; } $message = date("M d H:i:s ").get_current_user()."[".getmypid()."]: ".$message; if (!@file_exists($this->log_file) || !($fp = @fopen($this->log_file, "a"))) { $this->smtp_debug("Warning: Cannot open log file "".$this->log_file.""n"); return FALSE;; } flock($fp, LOCK_EX); fputs($fp, $message); fclose($fp);
}
{ $comment = "([^()]*)"; while (ereg($comment, $address)) { $address = ereg_replace($comment, "", $address); }
}
{ $address = ereg_replace("([ trn])+", "", $address); $address = ereg_replace("^.*<(.+)>.*$", "1", $address); return $address; } function smtp_debug($message) { if ($this->debug) { echo $message; } } } ?> |
发送邮箱的php文件
代码如下 | 复制代码 |
<?php require_once "email.class.php"; //******************** 配置信息 ******************************** $smtpserver = "smtp.126.com";//SMTP服务器 $smtpserverport =25;//SMTP服务器端口 $smtpusermail = "new2008oh@126.com";//SMTP服务器的用户邮箱 $smtpemailto = $_POST['toemail'];//发送给谁 $smtpuser = "new2008oh";//SMTP服务器的用户帐号 $smtppass = "您的邮箱密码";//SMTP服务器的用户密码 $mailtitle = $_POST['title'];//邮件主题 $mailcontent = "<h1>".$_POST['content']."</h1>";//邮件内容 $mailtype = "HTML";//邮件格式(HTML/TXT),TXT为文本邮件 //************************ 配置信息 **************************** $smtp = new smtp($smtpserver,$smtpserverport,true,$smtpuser,$smtppass);//这里面的一个true是表示使用身份验证,否则不使用身份验证. $smtp->debug = false;//是否显示发送的调试信息 $state = $smtp->sendmail($smtpemailto, $smtpusermail, $mailtitle, $mailcontent, $mailtype);
if($state==""){ echo "对不起,邮件发送失败!请检查邮箱填写是否有误。"; echo "<a href='index.html'>点此返回</a>"; exit(); } echo "恭喜!邮件发送成功!!"; echo "<a href='index.html'>点此返回</a>"; echo "</div>"; ?> |
效果截图欣赏:
填写收件人,标题和内容后提交
返回成功的提示
瞬间便接收到了邮件
smtp类无法发送邮件解决方法
偶然发现我网站后台自动发送邮件功能不能用了,报这个错误:
Trying to smtp.126.com:25 Error: Cannot connenct to relay host smtp.126.com Error: () Error: Cannot send email to web@daixiaorui.com state
大概意思是:无法connenct中继主机smtp.126.com 错误:()错误:无法发送电子邮件给web@daixiaorui.com
上网找了n多资料后终于找到了解决方案,不是smtp类的问题,而就是linux配置的问题。原来是服务器的php.ini 禁用了fsockopen函数。
打开空间下的php.ini文件,linux空间一般都可以自定义php.ini,所以根目录下面一般会有这个文件。
有两个地方可能禁用此函数:
1. allow_url_fopen = On 查看等于后面是否为 ON,如果为OFF时函数将被禁用
2. disable_functions = fsockopen pfsockopen (我的就是这样)这里应该去掉前面的“fsockopen”。使之变成:disable_functions = pfsockopen
改过之后,保存,再重新刷新页面,就发现在linux下能成功利用smtp类发送电子邮件了。感谢网友分享的方法,问题终于得到了解决。
php中使用smtp类轻松的发送电子邮件示例下载:http://file.111cn.net/upload/2013/12/13751999009017.zip
HPMailer 是一个专门用于php语言的邮件发送类,功能十分地强大,丰富了 PHP 本身单一的 mail() 函数。支持 SMTP 等、附件等。 PHPMailer 遵守 LGPL 授权,可以免费下载。
下载地址:http://sourceforge.net/projects/phpmailer/files/phpmailer%20for%20php5_6/PHPMailer%20v5.1/PHPMailer_v5.1.zip/download
使用方法(只说法邮件,其收邮件的功能飘过):
代码如下 | 复制代码 |
IsSMTP(); $mail->SMTPAuth = true; //smtp要求身份验证 $mail->SMTPSecure = 'ssl'; //smtp验证方式 $mail->Port = 465 ; //smtp端口号 $mail->Username = "username@gmail.com"; // 注册了的gmail用户邮箱(用你的gmail邮箱就可以) $mail->Password = "password"; //密码 $mail->Host = 'smtp.gmail.com'; // 发邮件的服务器 $mail->IsHTML(true); // 是否使支持 HTML 邮件的发送,默认为 false , $mail->From ='username@gmail.com'; // 发信人的邮箱,用你的gmail邮箱就可以 $mail->FromName = 'Mailer'; // 你的姓名 $mail->Subject = '邮件标题'; // 邮件标题 $mail->Body ='Hello world'; // 邮件内容,支持HTML代码 $mail->AddAddress('name@anydomain.com', 'First Last'); // 收件人邮箱和姓名 if (!$mail->Send()) { echo $mail->ErrorInfo; } |
本来一般是照上面的配置就可以通过指定的smtp服务器发送邮件了,但是经个人测试上面的设置只能用163,126的smtp发送邮件,像qq,gmail等都发送不出去! 在google上搜了N久,终于找到了下面的方法可以成功通过gmail发送邮件了,当然还包括:qq、sina、sohu等(雅虎的不能通过,貌似雅虎默认smtp没有开通,得开通他们的一个叫‘邮件提醒’功能才给你开通smtp/pop3)
下面是解决方法: 只需要在 class.phpmailer.php 中查找到下面的代码(可能由于下载的版本不同而稍微有点区别):
代码如下 | 复制代码 |
if(eregi(’^(.+):([0-9]+)$‘, $hosts[$index], $hostinfo)) { $host = $hostinfo[1]; $port = $hostinfo[2]; } else { $host = $hosts[$index]; $port = $this->Port; } |
更改为( 不任什么版本都改成下面的内容):
代码如下 | 复制代码 |
if(eregi(’^#(([a-z]+://)?[^:]+):(d+)#i‘, $hosts[$index], $hostinfo)) { $host = $hostinfo[1]; $port = $hostinfo[3]; } else { $host = $hosts[$index]; $port = $this->Port; } |
几经修改希望你也可以顺利的通过gmail的smtp发送邮件了(当然要在win下面要能发邮件,还得在IIS中安装smtp以及在php中有OpenSSL扩展的支持)。 最后经测试,这种修改后能顺利通过 126163qqgmailsinasohu的smtp发送邮件
mail函数是php自带的一个邮箱发送函数,但在各方法本人测试了都不如第三方插件好用,但是它有一个特点就是量不大的情况下使用方法快捷。
在我们平常使用PHP发送邮件时,不一定每次都需要使用像phpmailer这样强大的工具类,在网上找到一个不错的PHP mail封装函数,该函数能够解决以下使用mail()函数经常碰到的几个问题
1.怎样发送HTML格式邮件。
2.邮件主题填上中文是乱码。
3.收件人中除了填上收件人的邮件,还要填上名字,而且还是中文的。
4.发件人要填上网站的名字,让人收到邮件的时候不是光秃秃的显示邮件地址。// 对邮件地址进行中文的UTF-8编码转化
function format_mail_address($address){
if(preg_match("||", $address, $matches)){
$name = mb_substr($address, 0, strpos($address, '
函数的使用方法:
html_mail(
"电商沙龙",
array(
"用户A",
"用户B"),
"这是一封测试邮件",
”
需要说明的一点是,收件人为数组时,其中一个收件人查看邮件会看到所有其他收件人的邮件地址。如果要分开来发送(互相都看不见各自的邮件地址),可以使用循环一个个发送。使用加密抄送的方式可以实现隐藏加密抄送的邮件地址。
<?php
$to = $mailtoname . " <" . $mailtomail . "-->" ;
$mailsubject="邮件测试";
$mailheader = "X-Priority: 5n";
$mailheader.= "From: " . "Sales Teamn";
$mailheader.= "X-Sender: " . "support@ec-shalom.comn";
$mailheader.= "Return-Path: " . "support@ec-shalom.comn";
//普通抄送邮件
$mailheader.= "Cc: " . $mailcc ."n";
//加密抄送
$mailheader.= "Bcc: " . $mailbcc ."n";
$mailbody="电商沙龙-mail()函数发送邮件";
$result = mail ($to, $mailsubject, $mailbody, $mailheader);
echo "
Mail sent to “. “$to”. ” “; echo $mailsubject. ” “; echo $mailbody. ” “; echo $mailheader. ” “; if ($result) { echo “
<strong></strong><strong>Email sent successfully!</strong>
<strong>"; }else{ echo "</strong>
<strong></strong><strong>Email could not be sent. </strong>
<strong>"; } ?></strong>
注意了php mail函数是需要服务器的支持,此函数配置如下
装设置服务端
Windows XP和2000本身就拥有构件SMTP服务器的功能,只是一般还没有安装。选择“控制面板→添加/删除程序→添加/删除Windows组件”,弹出“Windows组件向导”对话框,在其中双击“Internet信息服务(IIS)”项,就会打开详细选择项,选中“SMTP Service”,按“确定”,插入Windows XP安装盘进行安装
安装好SMTP服务器后,选择“控制面板→性能和维护→管理工具→Internet信息服务”打开Internet信息服务设置窗口,在窗口左侧点击本地计算机名,展开本地计算机目录,可以看到有两个分支“Wed站点”和“默认SMTP虚拟服务器”。在“默认SMTP虚拟服务器”上点击鼠标右键选择“属性”,打开“默认SMTP虚拟服务器属性”窗口。
“常规”选项卡主要设置IP地址,单击IP地址下拉项选择“127.0.0.1”,表示指向本地计算机IP地址,其他项使用默认即可。如果你是局域网接入,拥有固定IP地址,那么IP地址就应该选择相应的地址
“访问”选项卡中设置访问权限。单击“身份验证”,选择“匿名访问”,表示任何用户都可以发送,其他两项不用选择;单击“连接控制”中的“连接”和“中段限制”中的“中断”,选中“仅以下列表除外”,表示可以许接入所有用户的访问。
“邮件”选项卡中设置邮件传输条件及限制,“限制邮件大小为”等四个选项可以使用默认值,无须更改;
“将未传递报告的副本发送到”可将发送不成功的邮件返回发件人,并且写明不成功的原因;“死信目录”设置没有发送成功的邮件被存放的位置。
“传输”选项中设置邮件传递时间,这里不用修改,使用默认值;“LDAP路由”选项用来指定服务器使用的目录服务器标识和属性,这里也不用启动它。
“安全”选项中设置使用发送服务器的有权用户,默认用户是“Administrators”,你可以单击“添加”添加使用用户。
一切设置好后,你就拥护了自己的邮件发送服务器了!
SMTP装好以后 你应该是在WINDOW2K下,你找到PHP。INI文件 在C:WINNT下
打开找到下面这些行
[mail function]
; For Win32 only.
SMTP = 10.0.0.9 -------》替换成你的IP,10.0.0.9是偶的IP了 :)
; For Win32 only.
sendmail_from = test@test.com ---》发件人信息
然后重新启动APACHE