PHP代码发送邮件

时间:2016-08-12 07:31:46

标签: php

是否需要在哪个站点使用代码的mailid?它显示已发送的邮件,但它不会向代码中提到的mailid发送任何内容。我怀疑从哪个emailid,邮件将被发送?为此,我要在我的域名上创建一个ID吗?

$msg=" ".$a." ".$b." ".$c." ".$d." ".$e;
$to="email@example.com";
$sub=$a;
$msg = wordwrap($msg, 70);
#echo $msg;

$r=mail($to,$sub,$msg);

     if( $r== true ) {
echo"<script>alert('mailsent');</script>";
     }else {
        echo"<script>alert('failure');</script>";
     }

我使用的代码:

the code i hav used

1 个答案:

答案 0 :(得分:1)

使用mail()发送电子邮件是不可靠的,你不知道电子邮件是否真的被发送,就像你发现将邮件传递给邮件一样,增加了邮件发送的可能性。

$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

if(mail($to, $sub, $msg, $headers)){
  echo "<p>Email Sent</p>";
} 

更好的方法是使用phpmailer - https://github.com/PHPMailer/PHPMailer

这是他们发送电子邮件的样本

require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

//$mail->SMTPDebug = 3;                               // Enable verbose debug output

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'user@example.com';                 // SMTP username
$mail->Password = 'secret';                           // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587;                                    // TCP port to connect to

$mail->setFrom('from@example.com', 'Mailer');
$mail->addAddress('joe@example.net', 'Joe User');     // Add a recipient
$mail->addAddress('ellen@example.com');               // Name is optional
$mail->addReplyTo('info@example.com', 'Information');
$mail->addCC('cc@example.com');
$mail->addBCC('bcc@example.com');

$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
$mail->isHTML(true);                                  // Set email format to HTML

$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}

PHPMailer非常灵活,可以使用很少的选项,它也可以配置为使用SMTP,然后电子邮件可以通过经过身份验证的帐户发送,甚至可以使用SendGrid等第三方电子邮件服务来传递和监控您的电子邮件。 https://sendgrid.com/