我想使用SendGrid SMTP服务从我网站的联系表单发送电子邮件。表单上的提交按钮只是吐出我的网站的空白版本,没有电子邮件发送到我的收件箱。
这是PHP代码:
<?php
require("class.phpmailer.php");
$mail = new PHPMailer();
// SMTP & Sendgrid settings
$mail->IsSMTP();
$mail->Host = "smtp.sendgrid.net";
$mail->Port = "465";
$mail->SMTPAuth = "true"; // Enable SMTP authentication
$mail->Username = "sendgrid username";
$mail->Password = "sendgrid password";
$mail->SMTPSecure = ''; // Enable encryption, 'ssl' also accepted
// Email headers and body
$mail->SetFrom("abc@123.com");
$mail->AddAddress("abc@123.com");
// Form fields
$Name = $_POST['Name'];
$Email = $_POST['Email'];
$Contact = $_POST['Contact'];
$Message = $_POST['Message'];
$mail->Subject = "Message from yoursite.com";
$mail->Body = "You have a new message from your contact form on site.com \n \n Name: $Name \n Email: $Email \n Contact: $Contact \n Message: $Message";
$mail->WordWrap = 50;
if(!$mail->Send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
}
else {
echo 'Message has been sent.';
}
header('Location: mywebsite.com');
?>
答案 0 :(得分:3)
以下是使用SendGrid API发送电子邮件的分步过程,
现在来到编码部分。以下列方式重构您的代码,
require_once('sendgrid-php/sendgrid-php.php');
$from = new SendGrid\Email(null, "SENDER'S_EMAIL_ADDRESS");
$subject = "Hello World from the SendGrid PHP Library!";
$to = new SendGrid\Email(null, "RECEIVER'S EMAIL ADDRESS");
$content = new SendGrid\Content("text/plain", "Hello, Email!");
$mail = new SendGrid\Mail($from, $subject, $to, $content);
$apiKey = 'YOUR_API_KEY';
$sg = new \SendGrid($apiKey);
$response = $sg->client->mail()->send()->post($mail);
if($response->statusCode() == 202){
echo "Email sent successfully";
}else{
echo "Email could not be sent";
}
请勿忘记根据您的要求更改SENDER'S_EMAIL_ADDRESS
,RECEIVER'S_EMAIL_ADDRESS
和YOUR_API_KEY
。最重要的是,根据您的应用程序要求更改电子邮件的主题和正文。
旁注:如果中途出现任何问题,请使用以下三种响应方法进行调试。
echo $response->statusCode();
var_dump($response->headers());
echo $response->body();