Search code examples
smtpphpmailersendgridsendgrid-api-v3

SendGrid only sends emails to Gmail


I'm trying to integrate SendGrid API via phpMailer (also tried with php API library too). In localhost and live server I got 250 OK with phpmailer and 202 OK with API library response.

After submission (4 receiver), I've only receive 1 email to gmail. Another domain email addresses shows Delivered in SendGrid activitiy page but I dont receive these emails except Gmail.

My sender email adress and domain address already verified. Whats wrong on my code?

phpMailer

$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->IsSMTP();
$mail->Host          = 'smtp.sendgrid.net';
$mail->Port          = 587;
$mail->Username      = 'apikey';
$mail->Password      = 'API_KEY';
$mail->SMTPAuth      = true;
$mail->SMTPDebug     = true;
$mail->Debugoutput   = 'html';
$mail->SMTPKeepAlive = true;
$mail->SMTPSecure = 'TLS';
$mail->Priority = 3;
$mail->Encoding = 'base64';
$mail->CharSet = "utf-8";
$mail->SetFrom('[email protected]', $name = 'Sender Title');
$mail->AddAddress('[email protected]', 'Receiver Title');
$mail->Subject  =  'SendGrid Test';
$mail->MsgHTML('Mail body');
$sending = $mail->Send();
$mail->SmtpClose();

With API Library

$email = new \SendGrid\Mail\Mail();
$email->setFrom("[email protected]", "Example User");
$email->setSubject("Sending with Twilio SendGrid is Fun");
$email->addTo("[email protected]", "Example User");
$email->addContent("text/plain", "and easy to do anywhere, even with PHP");
$email->addContent(
    "text/html", "<strong>and easy to do anywhere, even with PHP</strong>"
);
$sendgrid = new \SendGrid('API_KEY');
try {
    $response = $sendgrid->send($email);
    print $response->statusCode() . "\n";
    print_r($response->headers());
    print $response->body() . "\n";
} catch (Exception $e) {
    echo 'Caught exception: '. $e->getMessage() ."\n";
}

Solution

  • If your emails are sending successfully and being received by Gmail, then there is nothing wrong with your code (save for the minor issues that Synchro pointed out in the comments).

    Email deliverability isn't an exact science, so there could be something in the contents of your email that triggers mail blocking for some inboxes. I'd follow the guidelines in this article on email deliverability to ensure you are setting yourself up to get emails into inboxes.

    Beyond that, I would also set up the SendGrid Event Webhook. That will delivery you events based on what your emails are doing, including delivery events when an email is dropped, deferred, bounced, blocked or delivered. That may help you understand what is happening to your email.