PHP send mail

【Foreword】

    This article mainly summarizes the knowledge points related to PHP sending emails

 

【List】

(1) mail() function;

(2) Simple E-Mail (text email);

(3) Mail form;

(4) Two ways to send emails

 

【main body】

(1) mail() function

mail(to to, subject subject, message, headers, parameters)

    to Required, specifies the recipient.

   subject Required, specifies the subject. Comment: This parameter cannot contain any newline characters.

   message Required, defines the message to send. LF (\n) should be used to separate lines.

   headers Optional, specify additional headers, such as From, Cc and Bcc, use CRLF (\r\n) to separate additional headers

   parameters Optional, specify additional parameters for the mail sender.

 

(2) Simple E-Mail (text email)

   The easiest way to send email via PHP is to send a text email.

   The following example first declares variables ($to, $subject, $message, $from, $headers) and then uses these variables in the mail() function to send e-mail:

<?php
$to = "[email protected]";
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = "[email protected]";
$headers = "From: $from";
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
?>

 

(3) Mail form

   通过 PHP,能够在自己的站点制作一个反馈表单。下例向指定的 e-mail 地址发送了一条文本消息:

<?php
if (isset($_REQUEST['email'])){
  //如果填写了“电子邮件”,请发送电子邮件
  $email = $_REQUEST['email'] ; 
  $subject = $_REQUEST['subject'] ;
  $message = $_REQUEST['message'] ;
  mail( "[email protected]", "Subject: $subject",
  $message, "From: $email" );
  echo "Thank you for using our mail form";
  }else{
  //如果“电子邮件”没有填写,则显示表单
  echo "<form method='post' action='mailform.php'>
  Email: <input name='email' type='text' /><br />
  Subject: <input name='subject' type='text' /><br />
  Message:<br />
  <textarea name='message' rows='15' cols='40'>
  </textarea><br />
  <input type='submit' value="提交"/>
  </form>";
  }
?>

   Case explanation:

   First, check if the email input box is filled in

   If not filled (such as when the page is first accessed), output the HTML form; if filled (after the form is filled), send an email from the form. When the submit button is clicked, the page is reloaded and the message that the email was sent successfully is displayed

 

 (4) Two ways to send emails

      (1) Use PHP's built-in mail() function

      (2) Use the mail class that encapsulates the SMTP protocol

Next, we will introduce separately

 (1) Use PHP's built-in mail() function

    ①Initial code

<?php
$to = "[email protected]"; //Recipient
$subject = "Test"; //subject
$message = "This is a test mail!"; //正文
$from = "[email protected]";//Additional title
$headers = "From: $from";//Extra parameters
mail($to,$subject,$message,$headers);
?>
   At this time, it will directly report an error
Warning: mail(): Failed to connect to mailserver at "localhost" port 25, verify your
"SMTP" and "smtp_port" setting in php.ini or use ini_set()
   After the translation, I learned that SMTP is also required locally. I will introduce SMTP in a later article.

    ② Modified code

<?php
$to = "[email protected]"; //Recipient
$subject = "Test"; //subject
$message = "This is a test mail!"; //正文
$from = "[email protected]";//Additional title
$headers = "From: $from";//Extra parameters
ini_set('SMTP','smtp.163.com');//发件SMTP
ini_set('smtp_port',25);//Sending SMTP port
ini_set('sendmail_from',"[email protected]");//Sender's mailbox
mail($to,$subject,$message,$headers);
?>

    After running, it is found that the error is still reported

Warning: mail(): SMTP server response: 553 authentication is required,163 smtp12,
EMCowAAnjdrpf6daSTLfEA--.12614S2 1520926697
    Analysis of the reason : need to verify the information, how to write the verification information? Where to configure it? After referring to some articles with these questions, I came to the conclusion that using the mail() function to send emails requires a server that can send emails without SMTP authentication. But now SMTP basically requires authentication, so if you want to use it to send emails, you can only set up a local SMTP that does not require authentication.       Construction method : You can use the IIS that comes with Windows, or download other SMTP software from the Internet.

   Conclusion : To use the mail() function to send mail, you must have an SMTP that does not require authentication. In this case, the configuration work will be a little more, but it will be easier to use, and a few lines of code will do.   

 

 (2) Mail using the encapsulated SMTP protocol

      This method is relatively common, especially for the majority of students who do not have a server and purchase virtual hosts from the Internet, the first method is unrealistic, so it is better to use the SMTP protocol to send emails.

      However, to complete this work, you need to have a certain understanding of the SMTP protocol. Students who like to be hands-on can write one by themselves, and students who like to use it can download it from the Internet. There are many.

      不过我比较推荐使用PEAR扩展中的Mail类,功能强大:可以支持纯文本、HTML格式的邮件;各字段都可设置编码,正确配置不会出现中文乱码情况;可以支持附件等等。

      在服务器可以使用pear install Mail 命令快速安装,没有足够服务器权限的同学也可以直接下载类的PHP源码包含进来就可以了。

注意:Mail类依赖  Net/SMTP.php  和 Mail/mime.php ,要一块下载,使用时一块包含进来。

      下面我举例说明一下在Mail类发送邮件的方法吧,网上其他SMTP邮件类使用方法一块也类似:

<?php 
// Pear Mail 扩展 
require_once('Mail.php'); 
require_once('Mail/mime.php'); 
require_once('Net/SMTP.php'); 

$smtpinfo = array(); 
$smtpinfo["host"] = "smtp.163.com";//服务器名字 
$smtpinfo["port"] = "25"; //端口 
$smtpinfo["username"] = "[email protected]"; //发件人邮箱 
$smtpinfo["password"] = "password";//发件人邮箱密码 
$smtpinfo["timeout"] = 10;//网络超时时间,秒 
$smtpinfo["auth"] = true;//登录验证 
//$smtpinfo["debug"] = true;//调试模式 

// 收件人列表 
$mailAddr = array('[email protected]'); 
// 发件人显示信息 
$from = "Name <[email protected]>"; 
// 收件人显示信息 
$to = implode(',',$mailAddr); 
// 邮件标题 
$subject = "这是一封测试邮件"; 
// 邮件正文 
$content = "<h3>随便写点什么</h3>"; 
// 邮件正文类型,格式和编码 
$contentType = "text/html; charset=utf-8";
//换行符号 Linux: \n Windows: \r\n 
$crlf = "\n"; 
$mime = new Mail_mime($crlf); 
$mime->setHTMLBody($content); 

$param['text_charset'] = 'utf-8'; 
$param['html_charset'] = 'utf-8'; 
$param['head_charset'] = 'utf-8'; 

$body = $mime->get($param); 
$headers = array(); 
$headers["From"] = $from; 
$headers["To"] = $to; 
$headers["Subject"] = $subject; 
$headers["Content-Type"] = $contentType; 
$headers = $mime->headers($headers); 
  
$smtp =& Mail::factory("smtp", $smtpinfo); 
$mail = $smtp->send($mailAddr, $headers, $body); 
$smtp->disconnect(); 
if (PEAR::isError($mail)) { 
  //发送失败 
  echo 'Email sending failed: ' . $mail->getMessage()."\n"; 
} else{ 
  //发送成功 
  echo "success!\n"; 
}

   从网上找的SMTP类都是高度封装的,所以使用起来比上面会更简单,但使用方法都是比较相似的。

   结论:这种方式发送邮件无需装任何软件,只需要包含进来一个PHP类,然后多写几行配置代码,就可以了。并且网上有很多示例的代码,很多时候只要复制过来然后修改个别的几个参数就可以用了,所以会很方便,推荐使用此方法。

   

 

 

 

 

参考网址:https://www.2cto.com/kf/201601/484719.html

 

 

 

 

 

 

 

.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326152210&siteId=291194637