4

I'm trying to send a calendar invitation on outlook using php and sendgrid. So I need to create an ics file which is not the issue. The issue is that I need to set headers. Gmail recognizes the ics file as a calendar invitation but outlook does not. This is the entire code that I've come up with but I'm going nowhere in this. Please help. I've searched every blog to find out how I can add headers such as content-type and content-disposition in sendgrid but 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>
90abyss
  • 7,037
  • 19
  • 63
  • 94

1 Answers1

3

Unfortunately this is a limitation of the current web endpoint. For this use case you need to send over SMTP instead of HTTP. Use the smtpapi-php library to build your X-SMTPAPI headers if you're using them. Then build your SMTP message with your library of choice, add your custom headers (including X-SMTPAPI if needed), and send it.

Example using Swift Mailer as the 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');
}
bwest
  • 9,182
  • 3
  • 28
  • 58