• ThinkPHP邮件发送S(Smtp + Mail + phpmailer)


      三种邮件发送介绍:(Smtp,Mail以及phpmailer)ThinkPhp 框架下开发。

      邮件发送配置先前准备(用该账号做测试用):(这里用新浪邮箱服务器)将自己的新浪邮箱开通 POP3/SMTP服务:

    新浪邮箱中  :设置->账户下面的 POP3/SMTP服务 选择开通(然后一步一步完成开通)。

     客户端html代码:

     1 <body>
     2     <!--<h1>发送信息测试</h1>-->
     3     <div>请输入发送地址(1):<input id="adds" type="text" style="180px;" /></div>
     4     <div>主题:<input id="title" type="text" style="100px;" /></div>
     5     <div style="600px;vertical-align:top;">
     6         发送信息:
     7         <textarea id="msgbody" property="请输入需要发送的信息..." style="180px;height:100px;"></textarea>
     8     </div>
     9     <div>
    10         <input type="button" value="发送1" onclick="sendmsg()" />
    11     </div>
    12 <body>
    View Code

      js:

     1  <script>
     2         function sendmsg() {
     3             var id = document.getElementById("adds").value;
     4             var msg = document.getElementById("msgbody").value;
     5             var title = document.getElementById("title").value;
     6             var par = /^[a-zA-Z0-9_+.-]+@([a-zA-Z0-9-]+.)+[a-zA-Z0-9]{2,4}$/;
     7 
     8             if (id == "") {
     9                 alert("输入发送地址");
    10                 return;
    11             } else if (!par.exec(id)) {
    12                 alert("填写地址错误!");
    13                 return;
    14             }
    15             showloading();
    16             $.post('__ROOT__/Home/SendEmail/sendMails', { email: id,title:title, msg: msg }, function (data) {
    17                 if (data.status == 1) {
    18                     hideloading();
    19                    // try {
    20                         alert("信息发送成功!");
    21                         alert(data.data);
    22                    // } catch (e) {
    23                      //   alert(e.message);
    24                    // }
    25                 } else {
    26                     hideloading();
    27                     alert("未知错误!");
    28                 }
    29             }, 'json');
    30         }
    31 </script>
    View Code

     第一种:Smtp(PHP)

      1:在ThinkPHP/LibraryLibrary文件夹下新建一个文件夹  HomeClass,在HomeClass 文件夹下新建一个类 命名为:smtp.class.php。(网上能找到的)

      1 <?php
      2 class smtp
      3 {
      4     /* Public Variables */
      5     var $smtp_port;
      6     var $time_out;
      7     var $host_name;
      8     var $log_file;
      9     var $relay_host;
     10     var $debug;
     11     var $auth;
     12     var $user;
     13     var $pass;
     14 
     15     /* Private Variables */ 
     16     var $sock;
     17 
     18     /* Constractor */
     19 
     20     function smtp($relay_host = "", $smtp_port = 25,$auth = false,$user,$pass)
     21     {
     22         $this->debug = FALSE;
     23         $this->smtp_port = $smtp_port;
     24         $this->relay_host = $relay_host;
     25         $this->time_out = 30; //is used in fsockopen() 
     26         
     27         #
     28 
     29         $this->auth = $auth;//auth
     30         $this->user = $user;
     31         $this->pass = $pass;
     32         
     33         #
     34 
     35         $this->host_name = "localhost"; //is used in HELO command 
     36         $this->log_file = "";
     37         $this->sock = FALSE;
     38     }
     39     /* Main Function */
     40 
     41     function sendmail($to, $from, $subject = "", $body = "", $mailtype, $cc = "", $bcc = "", $additional_headers = "")
     42     {
     43         $mail_from = $this->get_address($this->strip_comment($from));
     44         $body = ereg_replace("(^|(
    ))(.)", "1.3", $body);
     45         $header = "MIME-Version:1.0
    ";
     46 
     47         if($mailtype=="HTML"){
     48             $header .= "Content-Type:text/html
    ";
     49         }
     50 
     51         $header .= "To: ".$to."
    ";
     52 
     53         if ($cc != "") {
     54             $header .= "Cc: ".$cc."
    ";
     55         }
     56 
     57         $header .= "From: 报名邮件.<".$from.">
    ";
     58         $header .= "Subject: ".$subject."
    ";
     59         $header .= $additional_headers;
     60         $header .= "Date: ".date("r")."
    ";
     61         $header .= "X-Mailer:By Redhat (PHP/".phpversion().")
    ";
     62         $utfheader=iconv("UTF-8","GB2312",$header);
     63         list($msec, $sec) = explode(" ", microtime());
     64 
     65         $header .= "Message-ID: <".date("YmdHis", $sec).".".($msec*1000000).".".$mail_from.">
    ";
     66 
     67         $TO = explode(",", $this->strip_comment($to));
     68 
     69         if ($cc != "") {
     70             $TO = array_merge($TO, explode(",", $this->strip_comment($cc)));
     71         }
     72 
     73 
     74         if ($bcc != "") {
     75             $TO = array_merge($TO, explode(",", $this->strip_comment($bcc)));
     76         }
     77 
     78         $sent = TRUE;
     79 
     80         foreach ($TO as $rcpt_to) {
     81             $rcpt_to = $this->get_address($rcpt_to);
     82             
     83             if (!$this->smtp_sockopen($rcpt_to)) {
     84                 $this->log_write("Error: Cannot send email to ".$rcpt_to."
    ");
     85                 $sent = FALSE;
     86                 continue;
     87             }
     88 
     89             if ($this->smtp_send($this->host_name, $mail_from, $rcpt_to, $utfheader, $body)) {
     90                 $this->log_write("E-mail has been sent to <".$rcpt_to.">
    ");
     91             } else {
     92                 $this->log_write("Error: Cannot send email to <".$rcpt_to.">
    ");
     93                 $sent = FALSE;
     94             }
     95 
     96             fclose($this->sock);
     97 
     98             $this->log_write("Disconnected from remote host
    ");
     99         }
    100         return $sent;
    101     }
    102 /* Private Functions */
    103     function smtp_send($helo, $from, $to, $header, $body = "")
    104     {
    105         if (!$this->smtp_putcmd("HELO", $helo)) {
    106 
    107             return $this->smtp_error("sending HELO command");
    108         }
    109 
    110         #auth
    111 
    112         if($this->auth){
    113             if (!$this->smtp_putcmd("AUTH LOGIN", base64_encode($this->user))) {
    114                 return $this->smtp_error("sending HELO command");
    115             }
    116 
    117             if (!$this->smtp_putcmd("", base64_encode($this->pass))) {
    118                 return $this->smtp_error("sending HELO command");
    119             }
    120         }
    121 
    122         #
    123 
    124         if (!$this->smtp_putcmd("MAIL", "FROM:<".$from.">")) {
    125             return $this->smtp_error("sending MAIL FROM command");
    126         }
    127 
    128         if (!$this->smtp_putcmd("RCPT", "TO:<".$to.">")) {
    129             return $this->smtp_error("sending RCPT TO command");
    130         }
    131 
    132         if (!$this->smtp_putcmd("DATA")) {
    133             return $this->smtp_error("sending DATA command");
    134         }
    135         if (!$this->smtp_message($header, $body)) {
    136             return $this->smtp_error("sending message");
    137         }
    138         if (!$this->smtp_eom()) {
    139             return $this->smtp_error("sending <CR><LF>.<CR><LF> [EOM]");
    140         }
    141         if (!$this->smtp_putcmd("QUIT")) {
    142             return $this->smtp_error("sending QUIT command");
    143         }
    144         return TRUE;
    145     }
    146 
    147     function smtp_sockopen($address)
    148     {
    149         if ($this->relay_host == "") {
    150             return $this->smtp_sockopen_mx($address);
    151         } else {
    152             return $this->smtp_sockopen_relay();
    153         }
    154     }
    155     function smtp_sockopen_relay()
    156     {
    157         $this->log_write("Trying to ".$this->relay_host.":".$this->smtp_port."
    ");
    158         $this->sock = @fsockopen($this->relay_host, $this->smtp_port, $errno, $errstr, $this->time_out);
    159         if (!($this->sock && $this->smtp_ok())) {
    160             $this->log_write("Error: Cannot connenct to relay host ".$this->relay_host."
    ");
    161             $this->log_write("Error: ".$errstr." (".$errno.")
    ");
    162             return FALSE;
    163         }
    164         $this->log_write("Connected to relay host ".$this->relay_host."
    ");
    165         return TRUE;
    166     }
    167 
    168     function smtp_sockopen_mx($address)
    169     {
    170         $domain = ereg_replace("^.+@([^@]+)$", "1", $address);
    171         if (!@getmxrr($domain, $MXHOSTS)) {
    172             $this->log_write("Error: Cannot resolve MX "".$domain.""
    ");
    173             return FALSE;
    174         }
    175         foreach ($MXHOSTS as $host) {
    176             $this->log_write("Trying to ".$host.":".$this->smtp_port."
    ");
    177             $this->sock = @fsockopen($host, $this->smtp_port, $errno, $errstr, $this->time_out);
    178             if (!($this->sock && $this->smtp_ok())) {
    179                 $this->log_write("Warning: Cannot connect to mx host ".$host."
    ");
    180                 $this->log_write("Error: ".$errstr." (".$errno.")
    ");
    181                 continue;
    182             }
    183             $this->log_write("Connected to mx host ".$host."
    ");
    184             return TRUE;
    185         }
    186         $this->log_write("Error: Cannot connect to any mx hosts (".implode(", ", $MXHOSTS).")
    ");
    187         return FALSE;
    188     }
    189 
    190     function smtp_message($header, $body)
    191     {
    192         fputs($this->sock, $header."
    ".$body);
    193         $this->smtp_debug("> ".str_replace("
    ", "
    "."> ", $header."
    > ".$body."
    > "));
    194         return TRUE;
    195     }
    196 
    197     function smtp_eom()
    198     {
    199         fputs($this->sock, "
    .
    ");
    200         $this->smtp_debug(". [EOM]
    ");
    201         return $this->smtp_ok();
    202     }
    203 
    204     function smtp_ok()
    205     {
    206         $response = str_replace("
    ", "", fgets($this->sock, 512));
    207         $this->smtp_debug($response."
    ");
    208         if (!ereg("^[23]", $response)) {
    209             fputs($this->sock, "QUIT
    ");
    210             fgets($this->sock, 512);
    211             $this->log_write("Error: Remote host returned "".$response.""
    ");
    212             return FALSE;
    213         }
    214         return TRUE;
    215     }
    216 
    217     function smtp_putcmd($cmd, $arg = "")
    218     {
    219         if ($arg != "") {
    220             if($cmd=="") $cmd = $arg;
    221             else $cmd = $cmd." ".$arg;
    222         }
    223         fputs($this->sock, $cmd."
    ");
    224         $this->smtp_debug("> ".$cmd."
    ");
    225         return $this->smtp_ok();
    226     }
    227 
    228     function smtp_error($string)
    229     {
    230         $this->log_write("Error: Error occurred while ".$string.".
    ");
    231         return FALSE;
    232     }
    233     
    234     function log_write($message)
    235     {
    236         $this->smtp_debug($message);
    237         if ($this->log_file == "") {
    238             return TRUE;
    239         }
    240         $message = date("M d H:i:s ").get_current_user()."[".getmypid()."]: ".$message;
    241         if (!@file_exists($this->log_file) || !($fp = @fopen($this->log_file, "a"))) {
    242             $this->smtp_debug("Warning: Cannot open log file "".$this->log_file.""
    ");
    243             return FALSE;;
    244         }
    245         flock($fp, LOCK_EX);
    246         fputs($fp, $message);
    247         fclose($fp);
    248         return TRUE;
    249     }
    250     
    251     function strip_comment($address)
    252     {
    253         $comment = "([^()]*)";
    254         while (ereg($comment, $address)) {
    255             $address = ereg_replace($comment, "", $address);
    256         }
    257         return $address;
    258     }
    259 
    260     function get_address($address)
    261     {
    262         $address = ereg_replace("([ 	
    ])+", "", $address);
    263         $address = ereg_replace("^.*<(.+)>.*$", "1", $address);
    264         return $address;
    265     }
    266     function smtp_debug($message)
    267     {
    268         if ($this->debug) {
    269         echo $message;
    270         }
    271     }
    272 }
    273 ?>
    View Code

      2:提交到的后台控制器  SendEmailController.class.php 

     1 public function sendmsg(){
     2         $email = I ( 'post.email' );
     3         $msgs = I('post.msg');
     4         $title=I('post.title');
     5         
     6         import("HomeClass.smtp");//引用发送邮件类
     7         
     8         $smtpserver     =     "smtp.sina.cn";//SMTP服务器
     9         $smtpserverport =    25;//SMTP服务器端口
    10         $smtpusermail     =     "******@sina.cn";//SMTP服务器的用户邮箱
    11         $smtpuser         =     "****";//SMTP服务器的用户帐号
    12         $smtppass         =     "*****";//SMTP服务器的用户密码
    13         
    14         $smtpemailto     =     $email;//发送给谁
    15         $mailsubject     =     $title;//邮件主题
    16         $mailtime        =    date("Y-m-d H:i:s");
    17         $mailbody         =     $msgs;//邮件内容
    18             
    19         $utfmailbody    =    iconv("UTF-8","GB2312",$mailbody);//转换邮件编码
    20         $mailtype         =     "TXT";//邮件格式(HTML/TXT),TXT为文本邮件
    21             
    22         $smtp = new smtp($smtpserver,$smtpserverport,true,$smtpuser,$smtppass);//这里面的一个true是表示使用身份验证,否则不使用身份验证.
    23         $smtp->debug = FALSE;//是否显示发送的调试信息 FALSE or TRUE
    24         
    25         $datas = $smtp->sendmail($smtpemailto, $smtpusermail, $mailsubject, $utfmailbody, $mailtype);
    26         
    27         $this->ajaxReturn ( array (
    28                 'data' => $datas,
    29                 'status' => 1
    30         ) );
    31     }
    View Code

         其中:$smtpusermail 为你的新浪邮箱账号,$smtpuser 为你新浪邮箱账号(邮箱去掉@sina.com),$smtppass  为你的邮箱密码。第一种邮件发送搞定,你可以发送邮件去另一个邮箱了!!!

        第二种:Mail(ThinkPHP)。

        1:配置服务器邮箱:在 Application/conf/config.php 文件中添加邮箱配置:

     1 'THINK_EMAIL' => array (
     2                 
     3                 'SMTP_HOST' => 'smtp.sina.cn',
     4                 'SMTP_PORT' => '25',
     5                 'SMTP_USER' => '******@sina.cn', // SMTP服务器用户名
     6                 'SMTP_PASS' => '******', // SMTP服务器密码
     7                 'FROM_EMAIL' => '******@sina.cn', // 发件人EMAIL
     8                 'FROM_NAME' => '****', // 发件人名称
     9                 'REPLY_EMAIL' => '', // 回复EMAIL(留空则为发件人EMAIL)
    10 
    11                 'REPLY_NAME' => '' 
    12         ),
    View Code

         SMTP_USER  与 FROM_EMAIL 可为同一 邮箱地址。

        2:在 HomeClass  文件夹下 新建一个类:Mail.class.php:(网上能找到)

     1 <?php
     2 
     3 namespace HomeClass;
     4 
     5 class Mail {
     6     /**
     7      * 系统邮件发送函数
     8      *
     9      * @param string $to
    10      *            接收邮件者邮箱
    11      * @param string $name
    12      *            接收邮件者名称
    13      * @param string $subject
    14      *            邮件主题
    15      * @param string $body
    16      *            邮件内容
    17      * @param string $attachment
    18      *            附件列表
    19      * @return boolean
    20      */
    21     function sendMail($to, $name, $subject = '', $body = '', $attachment = null) {
    22         $config = C ( 'THINK_EMAIL' );
    23         vendor ( 'PHPMailer.class#phpmailer' ); // 从PHPMailer目录导class.phpmailer.php类文件
    24         $mail = new PHPMailer (); // PHPMailer对象
    25         $mail->CharSet = 'UTF-8'; // 设定邮件编码,默认ISO-8859-1,如果发中文此项必须设置,否则乱码
    26         
    27         //$mail->AddAddress($address);//添加联系人
    28         
    29         $mail->IsSMTP (); // 设定使用SMTP服务
    30         $mail->SMTPDebug = 0; // 关闭SMTP调试功能
    31                               // 1 = errors and messages
    32                               // 2 = messages only
    33         $mail->SMTPAuth = true; // 启用 SMTP 验证功能
    34         //$mail->SMTPSecure = 'ssl'; // 使用安全协议
    35         $mail->Host = $config ['SMTP_HOST']; // SMTP 服务器
    36         $mail->Port = $config ['SMTP_PORT']; // SMTP服务器的端口号
    37         $mail->Username = $config ['SMTP_USER']; // SMTP服务器用户名
    38         $mail->Password = $config ['SMTP_PASS']; // SMTP服务器密码
    39         $mail->SetFrom ( $config ['FROM_EMAIL'], $config ['FROM_NAME'] );
    40         $replyEmail = $config ['REPLY_EMAIL'] ? $config ['REPLY_EMAIL'] : $config ['FROM_EMAIL'];
    41         $replyName = $config ['REPLY_NAME'] ? $config ['REPLY_NAME'] : $config ['FROM_NAME'];
    42         $mail->AddReplyTo ( $replyEmail, $replyName );
    43         $mail->Subject = $subject;
    44         
    45         $mail->MsgHTML ( $body );
    46         $mail->AddAddress ( $to, '亲' );
    47         if (is_array ( $attachment )) { // 添加附件
    48             foreach ( $attachment as $file ) {
    49                 is_file ( $file ) && $mail->AddAttachment ( $file );
    50             }
    51         }
    52         return $mail->Send () ? true : $mail->ErrorInfo;
    53     }
    54 }
    View Code

         3:将前面JS代码的post提交链接改为 __ROOT__/Home/SendEmail/sendMails2,在刚才的控制器 SendEmailController.class.php 中添加一个方法: sendMail2().

     1 public function sendMails2(){
     2         $email = I ( 'post.email' );
     3         $msgs = I('post.msg');
     4         $title=I('post.title');
     5         
     6         $msg = HomeClassMail::sendMail ( $email, $email, $title, $msgs );
     7         
     8         $this->ajaxReturn ( array (
     9                 'data' => $msg,
    10                 'status' => 1
    11         ) );
    12     }
    View Code

        第三种:PHPMailer(ThinkPHP)

      1:看看ThinkPHP框架的 Library/Vendor 文件夹下是否存在 文件夹  PHPMailer,如果不存在,则在网上找个加入在该文件夹下。

      2:将前面的JS提交链接改为 __ROOT__/Home/SendEmail/sendMails3 ,在控制器里添加方法 sendMail3():

     1 public function sendmsg3($sendto_email, $user_name='', $subject, $bodyurl)
     2     {    
     3 
     4         $email = I ( 'post.email' );
     5         $title=I('post.title');
     6         $msgs = I('post.msg');
     7 
     8         vendor ( 'PHPMailer.class#phpmailer' );
     9         $mail = new PHPMailer();
    10         $mail->IsSMTP();                  // send via SMTP
    11          
    12         $mail->Host = "smtp.sina.cn"; // SMTP 服务器
    13         $mail->Port = 25; // SMTP服务器的端口号
    14         $mail->SMTPAuth = true;           // turn on SMTP authentication
    15         $mail->Username = "*****@sina.cn"; // SMTP服务器用户名
    16         $mail->Password = "******"; // SMTP服务器密码
    17     
    18         $mail->From = "*******@sina.cn";      // 发件人邮箱
    19         //$mail->FromName = "****";;  // 发件人
    20     
    21         $mail->CharSet = "utf-8";   // 这里指定字符集!
    22         $mail->Encoding = "base64";
    23         
    24         if($user_name == '')
    25         {
    26             $user_name=$sendto_email;
    27         }
    28         $mail->AddAddress($sendto_email,$sendto_email);  // 收件人邮箱和姓名
    29     
    30         //$mail->WordWrap = 50; // set word wrap 换行字数
    31         //$mail->AddAttachment("/var/tmp/file.tar.gz"); // attachment 附件
    32         //$mail->AddAttachment("/tmp/image.jpg", "new.jpg");
    33         
    34         $mail->IsHTML(true);  // send as HTML
    35         // 邮件主题
    36         $mail->Subject = $subject;
    37 
    38         //$urls=urlencode($bodyurl);
    39         $mail->Body="Hi,欢迎注册!";
    40         $mail->AltBody = "text/html";
    41     
    42         if (!$mail->Send())
    43         {
    44             $mail->ClearAddresses();
    45             return "邮件错误信息: " . $mail->ErrorInfo;
    46             exit;
    47         }
    48         else
    49         {
    50             $mail->ClearAddresses();
    51             // $this->assign('waitSecond', 6);
    52             //            $this->success("注册成功,系统已经向您的邮箱:{$sendto_email}发送了一封激活邮件!请您尽快激活~~<br />");
    53             //$this->redirect('sendhtml', array('send' => 5,'email'=>$sendto_email));
    54             return "亲!已经向您的邮箱:{$sendto_email}发送了一封激活邮件!请您尽快激活~~";
    55         }
    56     }
    View Code

      现在可以给另一个邮箱发送邮件了!!!

                 发送邮件页面:

            

        接收到的邮件:

          

    注:以上配置我只在给新浪邮箱发送邮件时成功,给QQ邮箱发送邮件时都已失败而告终,还搞不懂是为啥??

         ThinkPHP官网邮件发送:  http://www.thinkphp.cn/code/32.html

      PHP邮件发送: http://www.oschina.net/code/snippet_1182150_25127

  • 相关阅读:
    Python 接口测试之结果集比较封装
    Python 接口测试之发送邮件封装
    Python 接口测试之接口请求方法封装
    Python 接口测试之获取接口数据封装
    Python 接口测试之接口关键字封装
    Python 接口测试之Excel表格数据操作方法封装
    [c++] 二级指针的原理
    [bug] java.text.ParseException: Unparseable date: "2020-01-01"
    [bug] IDEA编译时出现 Information:java: javacTask: 源发行版 1.8 需要目标发行版 1.8
    [bug] maven“1.5不支持diamond运算符,请使用source 7或更高版本以启用diamond运算符”
  • 原文地址:https://www.cnblogs.com/cj8988/p/4190029.html
Copyright © 2020-2023  润新知