我在一个网站上使用PHP,我想添加电子邮件功能。
我安装了WampServer。
如何使用PHP发送电子邮件?
我在一个网站上使用PHP,我想添加电子邮件功能。
我安装了WampServer。
如何使用PHP发送电子邮件?
当前回答
对于大多数项目,我现在使用Swift mailer。这是一种非常灵活和优雅的面向对象的发送电子邮件的方法,它是由给我们提供流行的Symfony框架和Twig模板引擎的同一个人创建的。
基本用法:
require 'mail/swift_required.php';
$message = Swift_Message::newInstance()
// The subject of your email
->setSubject('Jane Doe sends you a message')
// The from address(es)
->setFrom(array('jane.doe@gmail.com' => 'Jane Doe'))
// The to address(es)
->setTo(array('frank.stevens@gmail.com' => 'Frank Stevens'))
// Here, you put the content of your email
->setBody('<h3>New message</h3><p>Here goes the rest of my message</p>', 'text/html');
if (Swift_Mailer::newInstance(Swift_MailTransport::newInstance())->send($message)) {
echo json_encode([
"status" => "OK",
"message" => 'Your message has been sent!'
], JSON_PRETTY_PRINT);
} else {
echo json_encode([
"status" => "error",
"message" => 'Oops! Something went wrong!'
], JSON_PRETTY_PRINT);
}
有关如何使用Swift mailer的更多信息,请参阅官方文档。
其他回答
纯文本电子邮件
<?php
$to = 'name@example.com';
$subject = 'Your email subject here';
$message = 'Your message here';
// Carriage return type (RFC).
$eol = "\r\n";
$headers = "Reply-To: Name <name@example.com>".$eol;
$headers .= "Return-Path: Name <name@example.com>".$eol;
$headers .= "From: Name <name@example.com>".$eol;
$headers .= "Organization: Hostinger".$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-type: text/plain; charset=utf-8".$eol;
$headers .= "X-Priority: 3".$eol;
$headers .= "X-Mailer: PHP".phpversion().$eol;
mail($to, $subject, $message, $headers);
使用html发送电子邮件
<?php
$to = 'name@example.com';
$subject = 'Your email subject here';
$message = '
<html>
<head>
<title>Your '.$to.' as your contact email address</title>
</head>
<body>
<p>Hi, there!</p>
<p>It is a long established fact that '.$to.' reader will be distracted by the readable content of a page when looking at its layout</p>
</body>
</html>
';
// Carriage return type (RFC).
$eol = "\r\n";
$headers = "Reply-To: Name <name@example.com>".$eol;
$headers .= "Return-Path: Name <name@example.com>".$eol;
$headers .= "From: Name <name@example.com>".$eol;
$headers .= "Organization: Hostinger".$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-type: text/html; charset=iso-8859-1".$eol;
$headers .= "X-Priority: 3".$eol;
$headers .= "X-Mailer: PHP".phpversion().$eol;
mail($to, $subject, $message, $headers);
邮件附附件
<?php
$url = "https://c.xkcd.com/random/comic/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// Must be set to true so that PHP follows any "Location:" header.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// $a will contain all headers.
$a = curl_exec($ch);
// This is what you need, it will return you the last effective URL.
$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
$str = file_get_contents($url.'info.0.json');
$json = json_decode($str, true);
// Get file info.
$imageTitle = $json['title'];
// Image url.
$imageUrl = $json['img'];
// Image alt text.
$imageAlt = $json['alt'];
// Image file.
$imageFile = file_get_contents($imageUrl);
$tokens = explode('/', $imageUrl);
// File name.
$fileName = $tokens[(count($tokens) - 1)];
// File extension.
$ext = explode(".", $fileName);
// File type.
$fileType = $ext[1];
// File size.
$header = get_headers($imageUrl, true);
$fileSize = $header['Content-Length'];
$to = 'name@example.com';
$subject = "Enjoy reading today's most interesting XKCD comics";
$message = '
<html>
<head>
<title>Your email '.$to.' is listed in our XKCD comics subscribers.</title>
</head>
<body>
<h1>'.$imageTitle.'</h1>
<img src='.$imageUrl.' alt='.$imageAlt.'>
</body>
</html>';
// File.
$content = chunk_split(base64_encode($imageFile));
// A random hash will be necessary to send mixed content.
$semiRand = md5(time());
$mimeBoundary = '==Multipart_Boundary_x{$semiRand}x';
// Carriage return type (RFC).
$eol = "\r\n";
$headers = 'Reply-To: Name <name@example.com>'.$eol;
$headers .= 'Return-Path: Name <name@example.com>'.$eol;
$headers .= 'From: Name <name@example.com>'.$eol;
$headers .= 'Organization: Hostinger'.$eol;
$headers = 'MIME-Version: 1.0'.$eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"{$mimeBoundary}\"".$eol;
$headers .= 'Content-Transfer-Encoding: 7bit'.$eol;
$headers .= 'X-Priority: 3'.$eol;
$headers .= 'X-Mailer: PHP'.phpversion().$eol;
// Message.
$body = '--'.$mimeBoundary.$eol;
$body .= "Content-Type: text/html; charset=\"UTF-8\"".$eol;
$body .= 'Content-Transfer-Encoding: 7bit'.$eol;
$body .= $message.$eol;
// Attachment.
$body .= '--'.$mimeBoundary.$eol;
$body .= "Content-Type:{$fileType}; name=\"{$fileName}\"".$eol;
$body .= 'Content-Transfer-Encoding: base64'.$eol;
$body .= "Content-disposition: attachment; filename=\"{$fileName}\"".$eol;
$body .= 'X-Attachment-Id: '.rand(1000, 99999).$eol;
$body .= $content.$eol;
$body .= '--'.$mimeBoundary.'--';
$success = mail($to, $subject, $body, $headers);
if ($success === false) {
echo '<h3>Failure</h3>';
echo '<p>Failed to send email to '.$to.'</p>';
} else {
echo '<p>Your email has been sent to '.$to.' successfully.</p>';
}
电子邮件验证
<?php
function verifyLink() {
require 'db-connection.php';
$mysqli->select_db($dbname);
$sql = "SELECT `email`, `hash` FROM `Users` ORDER BY `active`";
$result = $mysqli->query($sql);
$row = $result->fetch_row();
if ($_SERVER['HTTPS'] !== '' && $_SERVER['HTTPS'] === 'on') {
return '<a href="https://'.$_SERVER['HTTP_HOST'].'/verify.php?email='.$row[0].'&hash='.$row[1].'">Verify contact email</a>';
} else {
return '<a href="http://'.$_SERVER['HTTP_HOST'].'/verify.php?email='.$row[0].'&hash='.$row[1].'">Verify contact email</a>';
}
$mysqli->close();
}
$to = 'name@example.com';
$subject = 'Verify your XKCD contact email address';
$message = '
<html>
<head>
<title>Verify '.$to.' as your contact email address</title>
</head>
<body>
<p>Hi, there!</p>
<p>Please verify that you want to use '.$to.' as the contact email address for your XKCD account</p>
<p>XKCD will use this email to tell you about interesting comics updates.</p>
<div>'.verifyLink().'</div>
<h3>Do not recognise this activity?</h3>
<p>If you did not add '.$to.' to your XKCD account, ignore this email and that address will not be added to your XKCD account. Someone may have made a mistake while typing their own email address.</p>
</body>
</html>
';
// Carriage return type (RFC).
$eol = "\r\n";
$headers = "Reply-To: Name <name@example.com>".$eol;
$headers .= "Return-Path: Name <name@example.com>".$eol;
$headers .= "From: Name <name@example.com>".$eol;
$headers .= "Organization: Hostinger".$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-type: text/html; charset=iso-8859-1".$eol;
$headers .= "X-Priority: 3".$eol;
$headers .= "X-Mailer: PHP".phpversion().$eol;
mail($to, $subject, $message, $headers);
我在cPanel中使用了这个方法,一切工作正常:
<?php
$dest = "destination@domain.tld";
$fromaddy = "cpaneluser@domain.tld";
mail("<$dest>","Test from php mail","Test","From:<$fromaddy>","-f$fromaddy");
?>
我尝试在我的快速时间,我有同样的问题,但经过适当的研究,我解决了它。以下是我的方法。您必须下载PHPMailer源文件,并在项目中手动包含所需的文件。
您可以从PHPMailer主页1下载带有源代码的ZIP文件,点击“克隆或下载”绿色按钮(在右侧),然后选择“下载ZIP”。在要保存源文件的目录中解压缩包。
1来自:GitHub。 第二步:打开“(来自Gmail地址)谷歌帐户”,执行以下步骤:
禁用谷歌帐号的双因素密码验证。
Turn on Less Security. Allow third party app. There you Go.. <?php use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; require 'PHPMailer/src/Exception.php'; require 'PHPMailer/src/PHPMailer.php'; require 'PHPMailer/src/SMTP.php'; session_start(); if (isset($_POST['send'])) { $email = $_POST['email']; $subject = $_POST['subject']; $message = "I am trying"; //Load composer's autoloader $mail = new PHPMailer(true); try { //Server settings $mail->isSMTP(); $mail->Host = 'smtp.gmail.com'; $mail->SMTPAuth = true; $mail->Username = 'youremail@gmail.com'; $mail->Password = 'password'; $mail->SMTPOptions = array( 'ssl' => array( 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true ) ); $mail->SMTPSecure = 'ssl'; $mail->Port = 465; //Send Email $mail->setFrom('youremail@gmail.com'); //Recipients $mail->addAddress($email); $mail->addReplyTo('youremail@gmail.com'); //Content $mail->isHTML(true); $mail->Subject = $subject; $mail->Body = $message; $mail->send(); $_SESSION['result'] = 'Message has been sent'; $_SESSION['status'] = 'ok'; } catch (Exception $e) { $_SESSION['result'] = 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo; $_SESSION['status'] = 'error'; echo 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo; } } header("location: forgotPassword.php");
使用PHPMailer通过邮件发送用户密码的步骤:
步骤1:首先,从GitHub下载PHPMailer软件包
您只需下载PHPMailer源文件并手动包含所需的文件。
您可以从PHPMailer主页[1]下载带有源代码的ZIP文件, 点击“克隆或下载”绿色按钮(右侧),然后选择“下载ZIP”。 在要保存源文件的目录中解压缩包。
[1] https://github.com/PHPMailer/PHPMailer
第二步:打开“(来自Gmail地址)谷歌帐户”,执行以下步骤:
禁用谷歌帐号的双因素密码验证。 打开Less Security。 允许第三方应用程序。
步骤3:尝试使用下面的代码(注意:在这里,我只提供了使用PHP和MySQL通过电子邮件发送用户密码的功能代码)
<?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>";
}
}
}
?>
更多信息请参考这些文档[1]:
[1]. https://alexwebdevelop.com/phpmailer-tutorial/
对于大多数项目,我现在使用Swift mailer。这是一种非常灵活和优雅的面向对象的发送电子邮件的方法,它是由给我们提供流行的Symfony框架和Twig模板引擎的同一个人创建的。
基本用法:
require 'mail/swift_required.php';
$message = Swift_Message::newInstance()
// The subject of your email
->setSubject('Jane Doe sends you a message')
// The from address(es)
->setFrom(array('jane.doe@gmail.com' => 'Jane Doe'))
// The to address(es)
->setTo(array('frank.stevens@gmail.com' => 'Frank Stevens'))
// Here, you put the content of your email
->setBody('<h3>New message</h3><p>Here goes the rest of my message</p>', 'text/html');
if (Swift_Mailer::newInstance(Swift_MailTransport::newInstance())->send($message)) {
echo json_encode([
"status" => "OK",
"message" => 'Your message has been sent!'
], JSON_PRETTY_PRINT);
} else {
echo json_encode([
"status" => "error",
"message" => 'Oops! Something went wrong!'
], JSON_PRETTY_PRINT);
}
有关如何使用Swift mailer的更多信息,请参阅官方文档。