温馨提示×

如何在PHP中发送邮件

PHP
小云
100
2023-08-29 15:15:30
栏目: 编程语言

要在PHP中发送邮件,您可以使用内置的mail函数或使用第三方库,如PHPMailer或SwiftMailer。

下面是使用mail函数发送邮件的示例代码:

$to = 'recipient@example.com';
$subject = 'Subject of the email';
$message = 'Body of the email';
$headers = 'From: sender@example.com' . "\r\n";
$headers .= 'Reply-To: sender@example.com' . "\r\n";
$headers .= 'X-Mailer: PHP/' . phpversion();
// 发送邮件
mail($to, $subject, $message, $headers);

这是使用PHPMailer库发送邮件的示例代码:

require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'sender@example.com';
$mail->Password = 'password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('sender@example.com', 'Sender Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->Subject = 'Subject of the email';
$mail->Body = 'Body of the email';
// 发送邮件
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}

这是使用SwiftMailer库发送邮件的示例代码:

require_once 'vendor/autoload.php';
$transport = (new Swift_SmtpTransport('smtp.example.com', 587, 'tls'))
->setUsername('sender@example.com')
->setPassword('password');
$mailer = new Swift_Mailer($transport);
$message = (new Swift_Message('Subject of the email'))
->setFrom(['sender@example.com' => 'Sender Name'])
->setTo(['recipient@example.com' => 'Recipient Name'])
->setBody('Body of the email');
// 发送邮件
$result = $mailer->send($message);
if($result) {
echo 'Message has been sent.';
} else {
echo 'Message could not be sent.';
}

请确保在代码中替换实际的邮件服务器和身份验证凭据,并根据需要进行其他设置,例如设置附件或HTML邮件。

0