共计 1449 个字符,预计需要花费 4 分钟才能阅读完成。
要在 PHP 中发送邮件,您可以使用内置的 mail 函数或使用第三方库,如 PHPMailer 或 SwiftMailer。
下面是使用 mail 函数发送邮件的示例代码:
$to = '[email protected]';
$subject = 'Subject of the email';
$message = 'Body of the email';
$headers = 'From: [email protected]' . "\r\n";
$headers .= 'Reply-To: [email protected]' . "\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 = '[email protected]';
$mail->Password = 'password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('[email protected]', 'Sender Name');
$mail->addAddress('[email protected]', '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('[email protected]')
->setPassword('password');
$mailer = new Swift_Mailer($transport);
$message = (new Swift_Message('Subject of the email'))
->setFrom(['[email protected]' => 'Sender Name'])
->setTo(['[email protected]' => '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 邮件。
丸趣 TV 网 – 提供最优质的资源集合!
正文完