[英]Send email using PHPMailer without SMTP authentication
我不经常使用 PHP,但是当我使用 PHP 并且需要编写一个函数来发送电子邮件时,我只使用了 mail() 函数。 我在共享托管服务上使用过它,但我总是收到来自……嗯……不是帐户的电子邮件? 机器人? 它甚至没有电子邮件地址。
这就是我此时想要实现的目标 - 向我发送电子邮件,而无需真正连接到 SMTP 服务器或通过身份验证。 如何使用 PHPMailer 做到这一点? 在我的情况下甚至可能吗? 如果你以某种方式得到了我的问题,这样的电子邮件是怎么称呼的? 那些……不是由……嗯……电子邮件帐户发送的?
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer-master\src\Exception.php';
require 'PHPMailer-master\src\PHPMailer.php';
require 'PHPMailer-master\src\SMTP.php';
$mail = new PHPMailer();
$mail->FromName = "A random name";
$mail->addAddress("myemail@gmail.com", "Recepient Name");
$mail->isHTML(true);
$mail->Subject = "Subject is here";
$mail->Body = "Hello, <br>test body ";
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message has been sent";
}
?>
这让我有点想笑……
不,电子邮件不能只是神奇地出现,但电子邮件用户帐户和地址之间不一定存在直接关联。
当您通过调用mail()
从共享主机帐户mail()
,邮件服务器知道您从哪个帐户发送邮件,因此有时不需要身份验证。 例如,这就是 GoDaddy 的运作方式。 不幸的是,这种方法很容易被滥用,因为通常没有什么可以阻止您对自己的身份撒谎。 这就是为什么此类服务通常 a) 糟糕且 b) 对于实际传递消息极其不可靠。
如果您没有指定“发件人”地址,服务器通常会根据它所拥有的信息进行补充——通常是您的用户帐户名,或运行脚本的用户名(例如www-data
),以及主机名您所在的服务器,通常类似于randomnumber.hostingprovider.example.com
。 查看您之前发送的邮件标题,您可能会看到类似的内容。
有时,对于给定共享服务器上的所有用户,此地址可能相同,因此您的交付声誉可能取决于其他人发送的内容,很可能是垃圾邮件、网络钓鱼、恶意软件等。
这种模糊性对于可交付性来说很糟糕,因此如果您在这样的系统上托管您的联系表单,那么期望来自它的消息最终会出现在垃圾邮件文件夹中。
如果您使用 SMTP 通过“正确”帐户发送邮件,您将获得更多控制权和可靠性,但不幸的是,一些托管服务提供商(再次是 GoDaddy)会阻止出站 SMTP 并强迫您使用他们的邮件服务器。 这是一种说法,如果您想发送将要送达的电子邮件,请使用合适的托管服务提供商。
一旦您控制了您的发送,您就可以准确地选择发送消息的地址,这受身份验证限制(包括 SPF、DKIM 和 DMARC 等)的约束,但那是另一回事了。
据我所知,这是可能的,并且每次都能正常工作。 去年我发现我使用 mail() 函数发送的电子邮件会立即进入我的垃圾邮件箱(以及其他人的垃圾箱),造成很大的混乱。 我升级到 PHPMailer 来解决这个问题,但我从未将它设置为使用 SMTP 并且工作得很好。
我的代码是:
$mail = new PHPMailer(true);
$html = $email->get(); // This gets a standard HTML Template to use as the base of the e-mail.
$title = 'Title for Inside the HTML';
$subject = 'The E-mail Subject';
$html = str_replace('[title]',$title,$html); //Use this to replace the [title] element in my HTML Template with $title.
$html = str_replace('[date]',date("F j, Y g:i A"),$html); // Again, replaces [date] in the HTML Template with the current date and time.
$body = 'Hello My Good Friend,<br>This is just a simple <strong>HTML Message</strong><br><br>Thank you.';
$html = str_replace('[body]',$body,$html); //Add my HTML Message to the HTML Template.
try {
//Recipients
$mail->setFrom('noreply@example.com', 'My Organization');
$mail->addAddress($row["email"], $row["fullname"]); // Add a recipient
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $html;
$mail->AltBody = strip_tags($html,'<br>');
$mail->send();
//Return Success Message
$rMsg .= '<div class="alert alert-success">
<strong>Success: </strong> We have e-mailed the warning.</div>';
} catch (Exception $e) {
$rMsg .= '<div class="alert alert-danger">
<strong>Error: </strong> There was an error e-mailing the warning.</div>';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.