如何使用 PHP 发送电子邮件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5335273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to send an email using PHP?
提问by user590849
I am using PHP on a website and I want to add emailing functionality.
我在网站上使用 PHP,我想添加电子邮件功能。
I have WAMPSERVER installed.
我安装了 WAMPSERVER。
How do I send an email using PHP?
如何使用 PHP 发送电子邮件?
回答by Muthu Kumaran
Using PHP's mail()
function it's possible. Remember mail function will not work on a Local server.
使用 PHP 的mail()
功能是可能的。记住邮件功能在本地服务器上不起作用。
<?php
$to = '[email protected]';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: [email protected]' . "\r\n" .
'Reply-To: [email protected]' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
?>
Reference:
参考:
回答by norteo
You could also use PHPMailer class at https://github.com/PHPMailer/PHPMailer.
您还可以在https://github.com/PHPMailer/PHPMailer使用 PHPMailer 类。
It allows you to use the mail function or use an smtp server transparently. It also handles HTML based emails and attachments so you don't have to write your own implementation.
它允许您透明地使用邮件功能或使用 smtp 服务器。它还处理基于 HTML 的电子邮件和附件,因此您不必编写自己的实现。
The class is stable and it is used by many other projects like Drupal, SugarCRM, Yii, and Joomla!
该类很稳定,并且被许多其他项目使用,例如 Drupal、SugarCRM、Yii 和 Joomla!
Here is an example from the page above:
这是上面页面中的一个示例:
<?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 = '[email protected]'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
$mail->From = '[email protected]';
$mail->FromName = 'Mailer';
$mail->addAddress('[email protected]', 'Joe User'); // Add a recipient
$mail->addAddress('[email protected]'); // Name is optional
$mail->addReplyTo('[email protected]', 'Information');
$mail->addCC('[email protected]');
$mail->addBCC('[email protected]');
$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';
}
回答by Sumoanand
If you are interested in html formatted email, make sure to pass Content-type: text/html;
in the header. Example:
如果您对 html 格式的电子邮件感兴趣,请确保传入Content-type: text/html;
标题。例子:
// multiple recipients
$to = '[email protected]' . ', '; // note the comma
$to .= '[email protected]';
// 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 <[email protected]>, Kelly <[email protected]>' . "\r\n";
$headers .= 'From: Birthday Reminder <[email protected]>' . "\r\n";
$headers .= 'Cc: [email protected]' . "\r\n";
$headers .= 'Bcc: [email protected]' . "\r\n";
// Mail it
mail($to, $subject, $message, $headers);
For more details, check php mailfunction.
有关更多详细信息,请查看 php邮件功能。
回答by Kevin S
Also look into the PEAR mail package Pear Mail Page
另请查看 PEAR 邮件包Pear Mail Page
It seems to be a little more robust than the standard mail() function that is built in (if the standard function isn't adequate).
它似乎比内置的标准 mail() 函数更健壮一些(如果标准函数不够用)。
Here is an excerpt from this page showing how it is used. PEAR Mail send() usage
这是此页面的摘录,显示了它是如何使用的。 PEAR 邮件发送() 用法
<?php
include('Mail.php');
$recipients = '[email protected]';
$headers['From'] = '[email protected]';
$headers['To'] = '[email protected]';
$headers['Subject'] = 'Test message';
$body = 'Test message';
$smtpinfo["host"] = "smtp.server.com";
$smtpinfo["port"] = "25";
$smtpinfo["auth"] = true;
$smtpinfo["username"] = "smtp_user";
$smtpinfo["password"] = "smtp_password";
// Create the mail object using the Mail::factory method
$mail_object =& Mail::factory("smtp", $smtpinfo);
$mail_object->send($recipients, $headers, $body);
?>
回答by John Slegers
For most projects, I use Swift mailerthese days. It's a very flexible and elegant object-oriented approach to sending emails, created by the same people who gave us the popular Symfony frameworkand Twig template engine.
对于大多数项目,我现在使用Swift 邮件程序。这是一种非常灵活和优雅的面向对象发送电子邮件的方法,由为我们提供流行的Symfony 框架和Twig 模板引擎的同一个人创建。
Basic usage :
基本用法:
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('[email protected]' => 'Jane Doe'))
// The to address(es)
->setTo(array('[email protected]' => '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);
}
See the official documentationfor more info on how to use Swift mailer.
有关如何使用 Swift 邮件程序的更多信息,请参阅官方文档。
回答by AMB
this is very basic method to send plain text email using mail function.
这是使用邮件功能发送纯文本电子邮件的非常基本的方法。
<?php
$to = '[email protected]';
$subject = 'This is subject';
$message = 'This is body of email';
$from = "From: FirstName LastName <[email protected]>";
mail($to,$subject,$message,$from);
回答by lyndact
Try this:
尝试这个:
<?php
$to = "[email protected]";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: [email protected]" . "\r\n" .
"CC: [email protected]";
mail($to,$subject,$txt,$headers);
?>
回答by Paulo Buchsbaum
The native PHP function mail()
does not work for me. It issues the message:
原生 PHP 函数mail()
对我不起作用。它发出消息:
503 This mail server requires authentication when attempting to send to a non-local e-mail address
503 尝试发送到非本地电子邮件地址时,此邮件服务器需要身份验证
So, I usually use PHPMailer
package
所以,我通常使用PHPMailer
包
I've downloaded the version 5.2.23 from: GitHub.
我已经从GitHub下载了 5.2.23 版本。
I've just picked 2 files and put them in my source PHP root
我刚刚选择了 2 个文件并将它们放在我的源 PHP 根目录中
class.phpmailer.php
class.smtp.php
class.phpmailer.php
class.smtp.php
In PHP, the file needs to be added
在PHP中,需要添加文件
require_once('class.smtp.php');
require_once('class.phpmailer.php');
After this, it's just code:
在此之后,它只是代码:
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 = "[email protected]";
$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();
}
It works like a charm
它就像一个魅力
回答by Ahtisham
For future readers: Try this if other answers don't work (As was the case with me):
对于未来的读者:如果其他答案不起作用,请尝试此操作(就像我的情况):
1.) Download PHPMailer, open the zip file and extract the folder to your project directory.
1.) 下载PHPMailer,打开 zip 文件并将文件夹解压缩到您的项目目录。
3.) Rename the extracted directory to PHPMailerand write the below code inside of your php script (the script must be outside of the PHPMailerfolder)
3.) 将解压后的目录重命名为PHPMailer并在您的 php 脚本中写入以下代码(该脚本必须在PHPMailer文件夹之外)
<?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 = '[email protected]'; // sender gmail host
$mail->Password = 'password'; // sender gmail host password
$mail->SMTPSecure = 'tls'; // for encrypted connection
$mail->Port = 587; // port for SMTP
$mail->setFrom('[email protected]', "Sender"); // sender's email and name
$mail->addAddress('[email protected]', "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;
}
?>
回答by Mr. HK
Full code example..
完整代码示例..
Try it once..
试一次。。
<?php
// Multiple recipients
$to = '[email protected], [email protected]'; // 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 <[email protected]>, Kelly <[email protected]>';
$headers[] = 'From: Birthday Reminder <[email protected]>';
$headers[] = 'Cc: [email protected]';
$headers[] = 'Bcc: [email protected]';
// Mail it
mail($to, $subject, $message, implode("\r\n", $headers));
?>