Send ics calendar invite using Swift Mailer and Send Grid - php

I'm trying to send a calendar invite to Gmail using sendgrid and swiftmailer. This is my entire code:
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php
require_once('path/to/lib/swift_required.php');
require('path/to/smtpapi-php.php');
$transport = \Swift_SmtpTransport::newInstance('smtp.sendgrid.net', 587);
$transport->setUsername('uname');
$transport->setPassword('pass');
$mailer = \Swift_Mailer::newInstance($transport);
$ical="BEGIN:VCALENDAR\r\n
PRODID:-//Microsoft Corporation//Outlook 14.0 MIMEDIR//EN\r\n
VERSION:2.0\r\n
METHOD:REQUEST\r\n
Content-Type: text/calendar; charset="utf-8"; name=“invite.ics"; method=REQUEST'."\r\n";
Content-Disposition: inline; filename=“invite.ics"'."\r\n;
BEGIN:VEVENT\r\n
ATTENDEE;CN=aaa#aaa.com;RSVP=
TRUE:mailto:aaa#aaa.com\r\n
CLASS:PUBLIC\r\n
CREATED:20110803T133418Z\r\n
DTEND:20150429T035959Z\r\n
DTSTAMP:20110803T095605Z\r\n
DTSTART:$20150429T170000Z\r\n
LAST-MODIFIED:20110803T133418Z\r\n
ORGANIZER;CN=\”bbb\”:mailto:
bbb#bbb.com\r\n
PRIORITY:5\r\n
SEQUENCE:0\r\n
SUMMARY;LANGUAGE=ro:New Event\r\n
TRANSP:OPAQUE\r\n
UID:".MD5(TIME())."-85d2-69b00dea0ad4\r\n
X-MICROSOFT-CDO-BUSYSTATUS:TENTATIVE\r\n
X-MICROSOFT-CDO-IMPORTANCE:1\r\n
X-MICROSOFT-CDO-INTENDEDSTATUS:BUSY\r\n
X-MICROSOFT-DISALLOW-COUNTER:FALSE\r\n
X-MS-OLK-AUTOSTARTCHECK:FALSE\r\n
X-MS-OLK-CONFTYPE:0\r\n
BEGIN:VALARM\r\n
TRIGGER:-PT15M\r\n
ACTION:DISPLAY\r\n
DESCRIPTION:Reminder\r\n
END:VALARM\r\n
END:VEVENT\r\n
END:VCALENDAR\r\n";
$attachment = Swift_Attachment::newInstance()
->setFilename("invite.ics")
->setContentType('multipart/alternative;charset=UTF-8;name="invite.ics";method=REQUEST')
->setBody($ical)
->setDisposition('inline;filename=invite.ics');
$message = new \Swift_Message();
$message->setTo(array('aaa#aaa.com'));
$message->setFrom('bbb#bbb.co');
$message->setSubject('Hello');
$message->attach($attachment);
try {
$response = $mailer->send($message);
print_r($response);
} catch(\Swift_TransportException $e) {
print_r('Bad username / password');
}
?>
</body>
</html>
What is happening is that it is sending the email with the ics attachment but gmail and outlook are not recognizing that its a calendar invite. Can you please help me?
I've used this link as reference:
ics file not recognized by outlook

Some problems I see immediately:
You are not specifying a text/calendar content type.
You are using the wrong quotes in the content-type header and various other places. (” instead of ").
You are embedding triple-newlines (\n\r\n) because you have both a real newline and a \r\n.
This might not fix it, but it's a starting point. I would recommend taking a good look at the source of the email you are sending, and compare it to a correctly working iMip invite. I'd assume it's not the only problem.

Related

PHP MailSo library and attachments

I'm trying to use MailSo library to create MIME message. I have got to the point where next step is to process attachments. Everything is fine when attachments are binary files but when I try to to add plain text attachment as follow
$rResource = "Some plain text goes here";
$sFileName = 'text.txt';
$iFileSize = \strlen("Some plain text goes here");
$bIsInline = false;
$bIsLinked = false;
$sCID = $metadataCID;
$aCustomContentTypeParams = array(\MailSo\Base\Enumerations\Encoding::QUOTED_PRINTABLE_LOWER);
$oMessage->Attachments()->Add(
\MailSo\Mime\Attachment::NewInstance(
$rResource,
$sFileName,
$iFileSize,
$bIsInline,
$bIsLinked,
$sCID,
$aCustomContentTypeParams
)
);
I expect to see that attachment as
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: quoted-printable
Content-Disposition: attachment; filename=text.txt
but it always forcing to base64 neither adding charset to content-type part as
Content-Type: text/plain; name="text.txt"
Content-Disposition: attachment; filename="text.txt"
Content-Transfer-Encoding: base64
Any tips on that?
It looks like MailSo library treats all attachments except message/rfc822 as binaries. It will require to rewrite or extend createNewMessageAttachmentBody() private function.

How to send email via SMTP using MailSo library (PHP)

I have a hard time to send multipart MIME message via SMTP using PHP library called MailSo. Provided two examples are limited. No word on how to create headers, message body, multipart MIME message itself and then send it.
Current webmail (Rainloop) is running on MailSo and I want to avoid using 3rd party library on top of MailSo. Going forward all email actions are stored in the Rainloop Actions.php file.
Based on that to create multipart MIME message I should to create $oMessage object (\MailSo\Mime\Message) and I'm able partially do that like to add subject, message ID, custom headers, message body text but going further I'm not able to set MIME boundaries (to store original message body as a boundary as well additional content type as text/plain) not talking about sending $oMessage object via SMTP.
Here is my test code so far:
include 'lib/MailSo/MailSo.php';
echo '<pre>';
$oLogger = \MailSo\Log\Logger::SingletonInstance()
->Add(\MailSo\Log\Drivers\Inline::NewInstance("\r\n", true))
;
$sToEmails = 'Me As Tester <tester#test.com>';
$oToEmails = \MailSo\Mime\EmailCollection::NewInstance($sToEmails);
$sFromEmails = 'Baba Ganush <no-replay#test.com>';
$oFromEmails = \MailSo\Mime\Email::NewInstance($sFromEmails);
$oMessage = \MailSo\Mime\Message::NewInstance();
$oMessage->RegenerateMessageId();
$oMessage->SetXMailer('RainLoop/1.0.0');
$oMessage->SetCustomHeader('test-header','test-header-value');
$oMessage->setSubject("Test message");
$oMessage->AddText('Generated message body goes here...');
$oMessage->SetFrom($oFromEmails);
$oMessage->SetTo($oToEmails);
$oLogger->WriteDump($oMessage);
Well, I have figured out how to send an email message created using MailSo library (w/o any attachments for now)
Example code below
if($oMessage){
$rMessageStream = \MailSo\Base\ResourceRegistry::CreateMemoryResource();
$iMessageStreamSize = \MailSo\Base\Utils::MultipleStreamWriter($oMessage->ToStream(true), array($rMessageStream), 8192, true, true, true);
}
$aToCollection = $oMessage->GetTo();
if ($aToCollection && $oFrom)
{
$sRawBody = #stream_get_contents($rMessageStream);
if (!empty($sRawBody))
{
$sMailTo = trim($aToCollection->ToString(true));
$sMailSubject = trim($oMessage->GetSubject());
$sMailSubject = 0 === strlen($sMailSubject) ? '' : \MailSo\Base\Utils::EncodeUnencodedValue(\MailSo\Base\Enumerations\Encoding::BASE64_SHORT, $sMailSubject);
$sMailHeaders = $sMailBody = '';
list($sMailHeaders, $sMailBody) = explode("\r\n\r\n", $sRawBody, 2);
unset($sRawBody);
$sMailHeaders = \MailSo\Base\Utils::RemoveHeaderFromHeaders($sMailHeaders, array(\MailSo\Mime\Enumerations\Header::TO_,\MailSo\Mime\Enumerations\Header::SUBJECT));
mail($sMailTo, $sMailSubject, $sMailBody, $sMailHeaders);
}
}

PHP: Sending Email with Cyrillic (Ukrainian text)

Problem with sending Cyrillic Email with PHP.
My side:
Server IIS - Database MsSQL - email server: Exchange 2010 /communication via PHP EWS/
Reciever is UA Goverment owned company with their specific software for receiving emails. It is working with MS Outlook /manually send/.
I tried send it as text /not html/ or i tried PHP Mailer, i also already tried with C# /all are not working with this specific company /on gmail or hotmail it's working fine//.
$ews = new ExchangeWebServices($server, $username, $password);
$msg = new EWSType_MessageType();
$toAddresses = array();
$toAddresses[0] = new EWSType_EmailAddressType();
$toAddresses[0]->EmailAddress =;
$toAddresses[0]->Name =;
$msg->ToRecipients = $toAddresses;
$fromAddress = new EWSType_EmailAddressType();
$fromAddress->EmailAddress =;
$fromAddress->Name =;
$msg->From = new EWSType_SingleRecipientType();
$msg->From->Mailbox = $fromAddress;
$msg->Subject = "Test";
$msg->Body = new EWSType_BodyType();
$msg->Body->BodyType = 'HTML'; //Text HTML
$msg->Body->_ = $UAText;
$msgRequest = new EWSType_CreateItemType();
$msgRequest->Items = new EWSType_NonEmptyArrayOfAllItemsType();
$msgRequest->Items->Message = $msg;
$msgRequest->MessageDisposition = 'SendAndSaveCopy';
$msgRequest->MessageDispositionSpecified = true;
$response = $ews->CreateItem($msgRequest);
var_dump($response);
Thank You,
If its working with an normal Outlook client, however not with your solution my first check would be to compare the header from two example emails (one from outlook and one from your solution). I think that the content-type is set correctly with Outlook however not with your solution.
So you might wish to set the content encoding to UTF-8 in your solution. So I assume the content inside $UAText is some HTML stuff. You might therefore wish to flag that part as UTF-8 via:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
and see how it works.
Additional you might wish to set the encoding directly inside your code via:
$ews = new ExchangeWebServices($host, $user, $password, ExchangeWebServices::VERSION_2007_SP1);
$msg = new EWSType_MessageType();
$msg->MimeContent = new EWSType_MimeContentType();
$msg->MimeContent->_ = base64_encode("Mime-Version: 1.0\r\n"
. "From: michael#contoso.com\r\n"
. "To: amy#contoso.com\r\n"
. "Subject: nothing\r\n"
. "Date: Tue, 15 Feb 2011 22:06:21 -0000\r\n"
. "Message-ID: <{0}>\r\n"
. "X-Experimental: some value\r\n"
. "\r\n"
. "I have nothing further to say.\r\n");
$msg->MimeContent->CharacterSet = 'UTF-8';
Note: Here is a good starting point regarding the content-type encoding option. You also might wish to check the official Microsoft howto here.

Outlook 2013 shows "not supported calendar message.ics", but Gmail, Outlook 2007 are fine

My PHP program generate a ics file, it works previously for most email clients, but I got an error for Outlook 2013, the filename of the ics file, named "not supported calendar message.ics", but when double click to open it shows the content correctly. I search the internet but cannot find any reason. Could anyone help in this situation?
Here is the generated ics example:
BEGIN:VCALENDAR
PRODID:-//MY COMPANY NAME//System iCal Generator//EN
VERSION:2.0
METHOD:REQUEST
BEGIN:VEVENT
DTSTART:20170314T180000Z
DTEND:20170314T210000Z
DTSTAMP:20170217T161443Z
ORGANIZER;CN=name of event here:mailto:email#demoemailaddress.com
ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:customer#demoemailaddress.com
SUMMARY:Test website for evet
DESCRIPTION:xyz
LOCATION:tbc
SEQUENCE:0
UID:ICAL_128_NTG47K1VYJ#www.companydomain.com
END:VEVENT
END:VCALENDAR
Thanks for the help!
An old one, but I'll go ahead and answer since it came up in my searches.
I had some problems with the newer Outlook being very particular about whether or not it would accept my event without weird issues...and a lot of it actually came down to proper line-endings. I had to make sure \r\n was used within the VCalendar code, but in PHP on Unix, I had to make sure that \n was used for the new lines in the actual e-mail. Here is some code that I have working with the latest Outlook, which uses string arrays so that the line-endings of each section is explicit and obvious:
Please note that this code does nothing to prevent header-injection.
Please use responsibly :)
<?php
date_default_timezone_set('America/New_York');
//CONFIGURE HERE
$fromName = "John Doe";
$fromEmail = "john.doe#example.com";
$toName = "Your Name";
$toEmail = isset($_GET['to']) ? $_GET['to'] : 'yourname#example.com';
$start = new DateTime('2017-08-15 15:00');
$end = new DateTime('2017-08-15 16:00');
$summary = "Hello World Event";
//END CONFIGURATION
$uid = "0123456789";
$headers = array();
$boundary = "_CAL_" . uniqid("B",true) . "_B_";
$headers[] = "MIME-Version: 1.0";
$headers[] = "Content-Type: multipart/alternative; boundary=\"".$boundary."\"";
$headers[] = "To: \"{$toName}\" <{$toEmail}>";
$headers[] = "From: \"{$fromName}\" <{$fromEmail}>";
$calendarLines = array(
"BEGIN:VCALENDAR",
"METHOD:REQUEST",
"PRODID:-//PHP//MeetingRequest//EN",
"VERSION:2.0",
"BEGIN:VEVENT",
"ORGANIZER;CN={$fromName}:MAILTO:{$fromEmail}",
"ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE;CN={$toName}:MAILTO:{$toEmail}",
"DESCRIPTION:{$summary}",
"SUMMARY:{$summary}",
"DTSTART:".$start->setTimezone(new DateTimeZone('UTC'))->format('Ymd\THis\Z'),
"DTEND:".$end->setTimezone(new DateTimeZone('UTC'))->format('Ymd\THis\Z'),
"UID:{$uid}",
"CLASS:PUBLIC",
"PRIORITY:5",
"DTSTAMP:".gmdate('Ymd\THis\Z'),
"TRANSP:OPAQUE",
"STATUS:CONFIRMED",
"SEQUENCE:0",
"LOCATION:123 Any Street",
"BEGIN:VALARM",
"ACTION:DISPLAY",
"DESCRIPTION:REMINDER",
"TRIGGER;RELATED=START:-PT15M",
"END:VALARM",
"END:VEVENT",
"END:VCALENDAR"
);
$calendarBase64 = base64_encode(implode("\r\n",$calendarLines));
//ensure we don't have lines longer than 70 characters for older computers:
$calendarResult = wordwrap($calendarBase64,68,"\n",true);
$emailLines = array(
"--{$boundary}",
"Content-Type: text/html; charset=\"iso - 8859 - 1\"",
"Content-Transfer-Encoding: quoted-printable",
"",
"<html><body>",
"<h1>Hello World</h1>",
"<p>This is a calendar event test</p>",
"</body></html>",
"",
"--{$boundary}",
"Content-Type: text/calendar; charset=\"utf - 8\"; method=REQUEST",
"Content-Transfer-Encoding: base64",
"",
$calendarResult,
"",
"--{$boundary}--"
);
$emailContent = implode("\n",$emailLines);
$headersResult = implode("\n",$headers);
mail($toEmail, $summary, $emailContent, $headersResult );
echo("<pre>".htmlentities($headersResult)."\n\n".htmlentities($emailContent)."</pre>");
echo("<br /><br />");
echo("<pre>".base64_decode($calendarResult)."</pre>");
Please feel free to add comments on applications/sites that this does or doesn't work with. Thx.
Try to create an appointment in Outlook and then save it using the .ics format. See How To Save A Selected Appointment As Ics File In Outlook? for more informaiton. Then you can open the saved file and compare its content with a generated programmatically one.
Testing your icalendar feed with the icalendar validator at https://icalendar.org/validator.html it found the ATTENDEE line is longer than 75 characters, which is the maximum line size for an icalendar file. Perhaps that is why it is not working?

utf-8 charset not working on contact form with PEAR Mail_mime

I've found and tried various solutions given in other questions about utf-encoding for special characters and other related problems, but without any success.
I have an html contact form that sends information to my mail address with a simple php script using PEAR Mail mime. I can send information containing special characters from my test site on localhost with no problems, but not after I uploaded to my server.
eg message:
Test special characters: é è ç à ô
after being sent from server becomes:
Test special characters: é è ç à ô
I am guessing it's an encoding problem from my web server, but am kinda stuck at how to resolve the problem.
The meta tags in file containing the form are set to:
<meta charset="utf-8">
and the form is specified to accept charset utf-8:
<form name="contact" method="post" action="assets/send_form.php" accept-charset="UTF-8">
I've also tried sending content from php file with:
header("Content-Type: text/html; charset= UTF-8");
as well as creating $headers for the message with 'Content-Type' = 'text/html; charset="UTF-8".
The relevant php code in my script:
//This section creates the email headers
$headerss=array();
$headerss['From']= $from_address;
$headerss['To']= $siteEmail;
$headerss['Subject']= $email_subject;
$headerss['Return-Path']= $contactEmail;
$headerss['Date']= date("r");
$headerss['Content-Type'] = 'text/html; charset="UTF-8"';
// This section creates the smtp inputs
$auth = array('host' => $host, 'port' => $port, 'auth' => true, 'username' => $username, 'password' => $password);
// create new Mail_mime instance, set utf-8 charset
$mail = new Mail_mime();
$mail -> setHTMLBody($email_message);
//CHECK THIS OUT FOR UTF-8 *****************************
$mimeparams=array();
$mimeparams['text_encoding']="7bit";
$mimeparams['text_charset']="UTF-8";
$mimeparams['html_charset']="UTF-8";
$mimeparams['head_charset']="UTF-8";
$mimeparams['eol']= "\n" ;
$body = $mail->get($mimeparams);
$headers = $mail->headers($headerss);
// This section send the email
$smtp = Mail::factory('smtp', $auth);
$sendmail = $smtp->send($siteEmail, $headers, $body);
Any help will be really appreciated. Thanks.
Try to put before
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
I experienced the same problem and my solution was to save the php file in same format, in UTF-8 as I had saved in ANSI format. That solved my problem anyway.

Categories