要在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郵件。