How do I add headers to sendgrid?

I am trying to send a calendar invitation in Outlook using php and sendgrid. So I need to create an ics file which is not a problem. The problem is I need to set the headers. Gmail recognizes the ics file as a calendar invitation, but Outlook does not. This is all the code I came up with, but I'm not going anywhere. Please help. I have looked through every blog to see how I can add headers such as content type and content location to sendgrid, to no avail.

<html>
<head>
    <title>PHP Test</title>
</head>
<body>

<?php

include("/Users/aaa/Downloads/sendgrid-php/sendgrid-php.php");
include('/Users/aaa/Downloads//smtpapi-php/smtpapi-php.php');


$sendgrid = new SendGrid("uname", "pass");
$email    = new SendGrid\Email();

$ical = "
Content-Type: text/calendar;method=request
MIME-Version: 1.0
BEGIN:VCALENDAR
METHOD:REQUEST
VERSION:2.0
PRODID:-//hacksw/handcal//NONSGML v1.0//EN
BEGIN:VEVENT
UID:" . md5(uniqid(mt_rand(), true)) . "@time.co
DTSTAMP:" . gmdate('Ymd').'T'. gmdate('His') . "Z
DTSTART:20150429T170000Z
DTEND:20150429T035959Z
SUMMARY:New event has been added
END:VEVENT
END:VCALENDAR";

$filename = "invite.ics";
$file = fopen($filename, 'w');
fwrite($file, $ical);
fclose($file);


$email->addTo("aaa@outlook.com")
    ->setFrom("aaa@example.com")
    ->setSubject("Subject")
    ->setAttachment($filename)
    ->addHeader('Content-Type', 'multipart/alternative')
    ->addHeader('Content-Disposition', 'inline');

$sendgrid->send($email);

var_dump($sendgrid);

try {
    $sendgrid->send($email);
} catch(\SendGrid\Exception $e) {
    echo $e->getCode();
    foreach($e->getErrors() as $er) {
        echo $er;
    }
}

?>

</body>
</html>

      

+3


source to share


1 answer


Unfortunately this is a limitation of the current web endpoint. For this use case, you need to send via SMTP instead of HTTP. Use a library smtpapi-php

to create X-SMTPAPI headers if you are using them. Then create your SMTP message with the library of your choice, add your own headers (including X-SMTPAPI if needed) and send them.

Example Using Swift Mailer as SMTP Transport



use Smtpapi\Header;

$transport = \Swift_SmtpTransport::newInstance('smtp.sendgrid.net', 587);
$transport->setUsername('sendgrid_username');
$transport->setPassword('sendgrid_password');

$mailer = \Swift_Mailer::newInstance($transport);

$message = new \Swift_Message();
$message->setTos(array('bar@blurdybloop.com'));
$message->setFrom('foo@blurdybloop.com');
$message->setSubject('Hello');
$message->setBody('%how% are you doing?');

$header = new Header();
$header->addSubstitution('%how%', array('Owl'));

$message_headers = $message->getHeaders();
$message_headers->addTextHeader(HEADER::NAME, $header->jsonString());

try {
    $response = $mailer->send($message);
    print_r($response);
} catch(\Swift_TransportException $e) {
    print_r('Bad username / password');
}

      

+3


source







All Articles