如何使用PHP发送电子邮件?
我在一个网站上使用PHP,我想添加电子邮件功能 我已经安装了 如何使用PHP发送电子邮件?可以使用PHP的函数。请记住,邮件功能在本地服务器上不起作用 参考:如何使用PHP发送电子邮件?,php,email,wamp,wampserver,Php,Email,Wamp,Wampserver,我在一个网站上使用PHP,我想添加电子邮件功能 我已经安装了 如何使用PHP发送电子邮件?可以使用PHP的函数。请记住,邮件功能在本地服务器上不起作用 参考: 也可以查看PEAR邮件包 如果标准功能不充分,它似乎比内置的标准邮件功能更健壮 下面是本页的一个摘录,展示了它是如何使用的 如果您对html格式的电子邮件感兴趣,请确保传递内容类型:text/html;在标题中。例如: // multiple recipients $to = 'aidan@example.com' . ', '; //
也可以查看PEAR邮件包 如果标准功能不充分,它似乎比内置的标准邮件功能更健壮 下面是本页的一个摘录,展示了它是如何使用的
如果您对html格式的电子邮件感兴趣,请确保传递内容类型:text/html;在标题中。例如:
// multiple recipients
$to = 'aidan@example.com' . ', '; // note the comma
$to .= 'wez@example.com';
// subject
$subject = 'Birthday Reminders for August';
// message
$message = '
<html>
<head>
<title>Birthday Reminders for August</title>
</head>
<body>
<p>Here are the birthdays upcoming in August!</p>
<table>
<tr>
<th>Person</th><th>Day</th><th>Month</th><th>Year</th>
</tr>
<tr>
<td>Joe</td><td>3rd</td><td>August</td><td>1970</td>
</tr>
<tr>
<td>Sally</td><td>17th</td><td>August</td><td>1973</td>
</tr>
</table>
</body>
</html>
';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= 'To: Mary <mary@example.com>, Kelly <kelly@example.com>' . "\r\n";
$headers .= 'From: Birthday Reminder <birthday@example.com>' . "\r\n";
$headers .= 'Cc: birthdayarchive@example.com' . "\r\n";
$headers .= 'Bcc: birthdaycheck@example.com' . "\r\n";
// Mail it
mail($to, $subject, $message, $headers);
有关更多详细信息,请查看php函数。您也可以在中使用PHPMailer类
<?php
$to = 'SomeOtherEmailAddress@Domain.com';
$subject = 'This is subject';
$message = 'This is body of email';
$from = "From: FirstName LastName <SomeEmailAddress@Domain.com>";
mail($to,$subject,$message,$from);
它允许您透明地使用邮件功能或使用smtp服务器。它还处理基于HTML的电子邮件和附件,因此您不必编写自己的实现
这个类是稳定的,它被许多其他项目使用,比如Drupal、SugarCRM、Yii和Joomla
以下是上一页的示例:
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$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 encryption, 'ssl' also accepted
$mail->From = 'from@example.com';
$mail->FromName = '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->WordWrap = 50; // Set word wrap to 50 characters
$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';
}
这是使用邮件功能发送纯文本电子邮件的最基本方法
<?php
$to = 'SomeOtherEmailAddress@Domain.com';
$subject = 'This is subject';
$message = 'This is body of email';
$from = "From: FirstName LastName <SomeEmailAddress@Domain.com>";
mail($to,$subject,$message,$from);
您可以使用邮戳、Sendgrid等邮件web服务 编辑:我现在就用。由于严格的筛选,我无法向雇主的组织发送提醒邮件。但只要你不给别人发垃圾邮件,Gmail就可以工作。试试这个:
<?php
$to = "somebody@example.com";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: webmaster@example.com" . "\r\n" .
"CC: somebodyelse@example.com";
mail($to,$subject,$txt,$headers);
?>
对于大多数项目,我使用这些天。这是一种非常灵活和优雅的面向对象的方法来发送电子邮件,它是由那些给我们提供流行和实用的电子邮件的人创建的
基本用法:
有关如何使用Swift Mail的更多信息,请参阅。完整代码示例
试试看
<?php
// Multiple recipients
$to = 'johny@example.com, sally@example.com'; // note the comma
// Subject
$subject = 'Birthday Reminders for August';
// Message
$message = '
<html>
<head>
<title>Birthday Reminders for August</title>
</head>
<body>
<p>Here are the birthdays upcoming in August!</p>
<table>
<tr>
<th>Person</th><th>Day</th><th>Month</th><th>Year</th>
</tr>
<tr>
<td>Johny</td><td>10th</td><td>August</td><td>1970</td>
</tr>
<tr>
<td>Sally</td><td>17th</td><td>August</td><td>1973</td>
</tr>
</table>
</body>
</html>
';
// To send HTML mail, the Content-type header must be set
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
// Additional headers
$headers[] = 'To: Mary <mary@example.com>, Kelly <kelly@example.com>';
$headers[] = 'From: Birthday Reminder <birthday@example.com>';
$headers[] = 'Cc: birthdayarchive@example.com';
$headers[] = 'Bcc: birthdaycheck@example.com';
// Mail it
mail($to, $subject, $message, implode("\r\n", $headers));
?>
已使用此脚本发送电子邮件
按“发送电子邮件”按钮后,电子邮件将发送至Test@example.com本机PHP函数mail对我不起作用。它发出信息:
503尝试发送邮件时,此邮件服务器需要身份验证
发送到非本地电子邮件地址
所以,我通常使用PHPMailer包
我已从以下位置下载了版本5.2.23:
我刚刚选择了2个文件,并将它们放在我的源PHP根目录中
class.phpmailer.php
class.smtp.php
在PHP中,需要添加文件
require_once('class.smtp.php');
require_once('class.phpmailer.php');
在这之后,它只是代码:
require_once('class.smtp.php');
require_once('class.phpmailer.php');
...
//----------------------------------------------
// Send an e-mail. Returns true if successful
//
// $to - destination
// $nameto - destination name
// $subject - e-mail subject
// $message - HTML e-mail body
// altmess - text alternative for HTML.
//----------------------------------------------
function sendmail($to,$nameto,$subject,$message,$altmess) {
$from = "yourcontact@yourdomain.com";
$namefrom = "yourname";
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->isSMTP(); // by SMTP
$mail->SMTPAuth = true; // user and password
$mail->Host = "localhost";
$mail->Port = 25;
$mail->Username = $from;
$mail->Password = "yourpassword";
$mail->SMTPSecure = ""; // options: 'ssl', 'tls' , ''
$mail->setFrom($from,$namefrom); // From (origin)
$mail->addCC($from,$namefrom); // There is also addBCC
$mail->Subject = $subject;
$mail->AltBody = $altmess;
$mail->Body = $message;
$mail->isHTML(); // Set HTML type
//$mail->addAttachment("attachment");
$mail->addAddress($to, $nameto);
return $mail->send();
}
它很有魅力
<?php
include "db_conn.php";//connection file
require "PHPMailerAutoload.php";// it will be in PHPMailer
require "class.smtp.php";// it will be in PHPMailer
require "class.phpmailer.php";// it will be in PHPMailer
$response = array();
$params = json_decode(file_get_contents("php://input"));
if(!empty($params->email_id)){
$email_id = $params->email_id;
$flag=false;
echo "something";
if(!filter_var($email_id, FILTER_VALIDATE_EMAIL))
{
$response['ERROR']='EMAIL address format error';
echo json_encode($response,JSON_UNESCAPED_SLASHES);
return;
}
$sql="SELECT * from sales where email_id ='$email_id' ";
$result = mysqli_query($conn,$sql);
$count = mysqli_num_rows($result);
$to = "demo@gmail.com";
$subject = "DEMO Subject";
$messageBody ="demo message .";
if($count ==0){
$response["valid"] = false;
$response["message"] = "User is not registered yet";
echo json_encode($response);
return;
}
else {
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPAuth = true; // authentication enabled
$mail->IsHTML(true);
$mail->SMTPSecure = 'ssl';//turn on to send html email
// $mail->Host = "ssl://smtp.zoho.com";
$mail->Host = "p3plcpnl0749.prod.phx3.secureserver.net";//you can use gmail
$mail->Port = 465;
$mail->Username = "demousername@example.com";
$mail->Password = "demopassword";
$mail->SetFrom("demousername@example.com", "Any demo alert");
$mail->Subject = $subject;
$mail->Body = $messageBody;
$mail->AddAddress($to);
echo "yes";
if(!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
else {
echo "Message has been sent successfully";
}
}
}
else{
$response["valid"] = false;
$response["message"] = "Required field(s) missing";
echo json_encode($response);
}
?>
上面的代码对我很有用。从PHP发送电子邮件的核心方法是使用其内置的邮件功能,但是有几个现成的SDK可以简化集成: 通过HTTP工作,因此可以避免SMTP端口块问题
另外,我受雇于Pepipost。对于未来的读者:如果其他答案与我的情况不同,请尝试以下方法: 一,。下载、打开zip文件并将文件夹解压缩到项目目录 三,。将提取的目录重命名为PHPMailer,并在php脚本中编写以下代码。脚本必须位于PHPMailer文件夹之外 如果需要,您可以进行测试,通过tinker进行测试,如下代码所示
# SSH into droplet
# go to project
$ php artisan tinker
$ Mail::send('errors.401', [], function ($message) { $message->to('emmanuelbarturen@gmail.com')->subject('this works!'); });
# check your mailbox
使用PHPMailer通过电子邮件发送用户密码的过程:
步骤1:首先,从GitHub下载PHPMailer包
您只需下载PHPMailer源文件并手动包含所需文件
您可以从PHPMailer主页[1]下载带有源代码的ZIP文件,
单击右侧的“克隆或下载”绿色按钮,然后选择“下载ZIP”。
将包解压缩到要保存源文件的目录中
[1]
步骤2:然后,从Gmail地址打开Google帐户并执行以下步骤:
禁用谷歌帐户中的双因素密码验证。
打开较少的安全性。
允许第三方应用。
步骤3:尝试使用下面的代码注意:这里,我只提供了使用PHP和MySQL通过电子邮件发送用户密码的功能代码
有关更多信息,请参阅这些文件[1]:
[1] 如果我需要从本地服务器发送电子邮件,请阅读。我的意思是,有没有办法访问最近的邮件服务器,让它为我发送邮件。我的意思是,我可以找到一个雅虎邮件服务器的地址,然后我使用该服务器进行邮件发送。。。这可能吗?您需要在本地服务器上配置SMTP。看看这篇类似的帖子,Hello@MuthuKumaran如果垃圾邮件中出现了这个问题,有没有好的解决方案,请回答。@MuhammadAshikuzzaman你不能用PHP解决垃圾邮件问题。如果这仍然相关,请在相应的StackExchange站点上提出新问题。如何确保或验证这在我的本地服务器上是否有效?如果没有可行的方法,请提出一些替代方案。谢谢。你好,我厌倦了这个代码,我添加了3个收件人,一个Hotmail,一个Gmail,还有一个我的网站电子邮件。除了Hotmail,我收到了所有的邮件。你知道为什么它不适用于Hotmail吗?请检查垃圾邮件文件夹。我已经知道了,不是我
在垃圾邮件中,它根本无法到达。我读了更多关于这个主题的文章,似乎Hotmail需要一些特殊的标题,或者它不允许邮件通过他们的服务器。。。但我仍然没有找到解决方案。我通过使用PHPMailer解决了我的问题,并在PHPMailer的电子邮件对象中使用SSL输入我的电子邮件帐户数据。如果邮件包含HTML和php内容,该怎么办?请提供您使用的mail.php链接和文件夹中所有其他关联文件的下载链接。Thanks@Ashik我的示例中引用的Mail.php文件是Pear邮件包的一部分。如果下载并安装Pear邮件包,您将能够包含Mail.php。如果您单击上面的“Pear邮件页面”链接,则会有一个包含instructions.Hi的下载链接。当你的文档链接上写着Swift\u SendmailTransport时,你说的是Swift\u MailTransport。这是否意味着你指的是斯威夫特·梅勒的旧版本,或者是打字错误,或者是我误解了什么?我需要安装旧版本的swift mailer,因为我的服务器上没有php7。所以我需要知道当前版本的文档是否会与包的旧版本一起使用。谢谢。@YevgeniyAfanasyev:两年前我的回答是正确的,但是。无论如何,如果不能在项目中使用PHP7,那么应该使用SwiftMailerV5.4.9。这是最后一个仍然支持PHP5的稳定版本。有关v5.4.9版本的文档或v5.4.9与v6.0.2之间差异的详细信息,您可能需要联系或提出问题。非常感谢。因此,当分发版本可用时,没有适合旧版本的文档。很高兴知道。你受雇于Pepipost,你把Pepipost排在第三位+1@GeneCode,如果某样东西是最好的,那么它就是。不管你是否受雇于他们:Swiftmailer和PHPMailer绝对是发送电子邮件的最好的开源工具之一,因此我将它们保存在1和2中。但是,同时,它们也有一些限制和障碍,我们试图在Pepipost SDK中解决这些限制和障碍。@DibyaSahoo,这对您有很大的影响谢谢您的回答。您的建议与@norteo在其回答中指出的相同。请记住,v5.2已弃用,且未收到安全更新。对于v6,您可以直接要求:使用PHPMailer\PHPMailer\PHPMailer;使用PHPMailer\PHPMailer\Exception;需要_once'src/PHPMailer.php';需要_once'src/Exception.php';如果不使用编写器:使用PHPMailer\PHPMailer\PHPMailer;使用PHPMailer\PHPMailer\Exception;需要_once'src/PHPMailer.php';需要_once'src/Exception.php';在端口465上使用gmail时,您需要将主机设置为$mail->host=ssl://smtp.gmail.com';指示禁用2FA并启用较低的安全性,从而危及其他帐户,如果不是恶意的,至少是疏忽。相反,添加应用程序密码应该有效,同时保持帐户处于不太安全的状态。嗨@Skgland,很抱歉问这个问题,你提到的应用程序密码应该有效。您能告诉我如何在这个代码中使用它吗?您可以创建一个应用程序密码来代替您的帐户密码,而不是禁用2FA和启用较少的安全性。我只是用上面的源代码对它进行了测试,虽然简化为不使用db,只发送一封静态电子邮件,但为了进行测试,我还需要替换所需的行,因为我无法修改autoloder.php文件。
require_once('class.smtp.php');
require_once('class.phpmailer.php');
...
//----------------------------------------------
// Send an e-mail. Returns true if successful
//
// $to - destination
// $nameto - destination name
// $subject - e-mail subject
// $message - HTML e-mail body
// altmess - text alternative for HTML.
//----------------------------------------------
function sendmail($to,$nameto,$subject,$message,$altmess) {
$from = "yourcontact@yourdomain.com";
$namefrom = "yourname";
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->isSMTP(); // by SMTP
$mail->SMTPAuth = true; // user and password
$mail->Host = "localhost";
$mail->Port = 25;
$mail->Username = $from;
$mail->Password = "yourpassword";
$mail->SMTPSecure = ""; // options: 'ssl', 'tls' , ''
$mail->setFrom($from,$namefrom); // From (origin)
$mail->addCC($from,$namefrom); // There is also addBCC
$mail->Subject = $subject;
$mail->AltBody = $altmess;
$mail->Body = $message;
$mail->isHTML(); // Set HTML type
//$mail->addAttachment("attachment");
$mail->addAddress($to, $nameto);
return $mail->send();
}
<?php
include "db_conn.php";//connection file
require "PHPMailerAutoload.php";// it will be in PHPMailer
require "class.smtp.php";// it will be in PHPMailer
require "class.phpmailer.php";// it will be in PHPMailer
$response = array();
$params = json_decode(file_get_contents("php://input"));
if(!empty($params->email_id)){
$email_id = $params->email_id;
$flag=false;
echo "something";
if(!filter_var($email_id, FILTER_VALIDATE_EMAIL))
{
$response['ERROR']='EMAIL address format error';
echo json_encode($response,JSON_UNESCAPED_SLASHES);
return;
}
$sql="SELECT * from sales where email_id ='$email_id' ";
$result = mysqli_query($conn,$sql);
$count = mysqli_num_rows($result);
$to = "demo@gmail.com";
$subject = "DEMO Subject";
$messageBody ="demo message .";
if($count ==0){
$response["valid"] = false;
$response["message"] = "User is not registered yet";
echo json_encode($response);
return;
}
else {
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPAuth = true; // authentication enabled
$mail->IsHTML(true);
$mail->SMTPSecure = 'ssl';//turn on to send html email
// $mail->Host = "ssl://smtp.zoho.com";
$mail->Host = "p3plcpnl0749.prod.phx3.secureserver.net";//you can use gmail
$mail->Port = 465;
$mail->Username = "demousername@example.com";
$mail->Password = "demopassword";
$mail->SetFrom("demousername@example.com", "Any demo alert");
$mail->Subject = $subject;
$mail->Body = $messageBody;
$mail->AddAddress($to);
echo "yes";
if(!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
else {
echo "Message has been sent successfully";
}
}
}
else{
$response["valid"] = false;
$response["message"] = "Required field(s) missing";
echo json_encode($response);
}
?>
<?php
// PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
// Base files
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
// create object of PHPMailer class with boolean parameter which sets/unsets exception.
$mail = new PHPMailer(true);
try {
$mail->isSMTP(); // using SMTP protocol
$mail->Host = 'smtp.gmail.com'; // SMTP host as gmail
$mail->SMTPAuth = true; // enable smtp authentication
$mail->Username = 'sender@gmail.com'; // sender gmail host
$mail->Password = 'password'; // sender gmail host password
$mail->SMTPSecure = 'tls'; // for encrypted connection
$mail->Port = 587; // port for SMTP
$mail->setFrom('sender@gmail.com', "Sender"); // sender's email and name
$mail->addAddress('receiver@gmail.com', "Receiver"); // receiver's email and name
$mail->Subject = 'Test subject';
$mail->Body = 'Test body';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) { // handle error.
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
?>
# SSH into droplet
# go to project
$ php artisan tinker
$ Mail::send('errors.401', [], function ($message) { $message->to('emmanuelbarturen@gmail.com')->subject('this works!'); });
# check your mailbox
Tested 100% Work
<?php
session_start();
use PHPMailer\PHPMailer\PHPMailer; //add use in starting of the code
$db = mysqli_connect('localhost', 'root', '', '[Enter your Database Name]'); // connect to database
if (isset($_POST['forgot_btn'])) {
forgotpassword();
}
function forgotpassword(){
global $db;
$user_id = $_POST['user_id'];
$result = mysqli_query($db,"SELECT * FROM users where user_id='$user_id'");
$row = mysqli_fetch_assoc($result);
$fetch_user_id=$row['user_id'];
$name=$row['name'];
$email_id=$row['email_id'];
$password=$row['password'];
if($user_id==$fetch_user_id) {
require '../PHPMailer/vendor/autoload.php'; //Please correctly mention the PHPMailer installed directory (Don't follow my directory)
$mail = new PHPMailer(TRUE);
try{
$mail->setFrom('[Enter your From Email_Address]', '[Enter Sender Name]');
$mail->addAddress($email_id, $name); //[To Email Address and Name]
$mail->Subject = 'Regarding Forgot Password';
$mail->Body = 'Hi '.$name.',Your Login Password is:'.$password.'';
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = TRUE;
$mail->SMTPSecure = 'tls';
$mail->Username = '[Enter your From Email_Address]';
$mail->Password = '[Enter your From Email_Address -> Password]';
$mail->Port = 587;
if($mail->send())
{
echo "<script>alert('Password Sent Successfully');</script>";
}
else
{
echo "<script>alert('Please Check Your Internet Connection or From Email Address/Password or Wrong To Email Address');</script>";
}
}
catch (Exception $e)
{
echo "<script>alert('Please Check Your Internet Connection or From Email Address/Password or Wrong To Email Address');</script>";
}
}
}
?>