gpt4 book ai didi

PHP 使用 SMTP 发送电子邮件密件抄送和抄送

转载 作者:行者123 更新时间:2023-12-04 02:03:37 27 4
gpt4 key购买 nike

我有一个 PHP 代码可以将电子邮件发送到 cc 和 bcc。

在这种情况下,cc 不起作用。我测试了它并在我的电子邮件中看到没有抄送电子邮件。 (BCC 电子邮件有效)

这是我的代码:

require_once "Mail.php";

$from = "WEBAPPS <donotreply@test.com>";
$subject = "Calibration will be expiring!";

$host = 'smtp.office365.com';
$port = '587';
$username = 'donotreply@test';
$password = 'w00ew?';

$to = "alwis.david@gmail.com";
$cc = "data.gw@gmail.com";
$bcc = "hidayurie.dave@yahoo.com";

$body = "aa";

$headers = array(
'Port' => $port,
'From' => $from,
'To' => $to,
'Subject' => $subject,
'Content-Type' => 'text/html; charset=UTF-8'
);

$recipients = $to.", ".$cc.", ".$bcc;

$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));

$mail = $smtp->send($recipients, $headers, $body);

if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
} else {
echo("<p>Message successfully sent!</p>");
}

为什么 CC 不起作用?以及如何解决?

最佳答案

在上面的代码中,所有的接收者看起来都是一样的。

$recipients = $to.", ".$cc.", ".$bcc;

您可以在 https://github.com/PHPMailer/PHPMailer 使用 PHPMailer 类.这是一个用户友好的库。

<?php
require 'PHPMailerAutoload.php';

$mail = new PHPMailer;
//$mail = new PHPMailer(true); //turn on the exception, it will throw exceptions on errors
//$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
if (!empty($recipientArr)) { //have mutiple recepients
foreach ($recipientArr AS $eachAddress) {
$mail->addAddress($eachAddress);
}
}
$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';
}

关于PHP 使用 SMTP 发送电子邮件密件抄送和抄送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45581914/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com