Sending an HTML email using Swift - email

I would like to send an auto-generated email with HTML body from my application using Swift.
Here is my current code:
$message = Swift_Message::newInstance()
->setFrom(array('dummy1#test.com' => 'John Doe'))
->setTo('dymmy2#test.com')
->setSubject('some subject');
$message->setBody($this->getPartial('global/mail_partial'));
$this->getMailer()->send($message);
I had already tried to change the header Content-type of the email message using some specific Swift methods but it is not working.

See:
Sending a HTML E-Mail (from SwiftMailer Docs)
You need to add this line to set html content-type:
$message->setContentType("text/html");
Alternatively, it can by done passing a second argument on the $message->setBody() method:
$message->setBody($this->getPartial('global/mail_partial'), 'text/html');.

Related

How to get the correct formatting in an Email when using Google Sheets and App Script

I'm trying to send a bunch of mails to a list of contacts that I have saved in Google Sheets.
I copied the code to send the emails, but the emails that are sent aren't in the format that I need them in, and are getting converted to plaintext when being sent.
Any help on how to get around this issue?
P.S. My coding knowledge is nil, and I just copied the code from this website : https://productivityspot.com/automatically-send-emails-from-google-sheets/
The code I used is below:
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var sheet1=ss.getSheetByName('Sheet1');
var sheet2=ss.getSheetByName('Sheet2');
var subject = sheet2.getRange(2,1).getValue();
var n=sheet1.getLastRow();
for (var i = 2; i < n+1 ; i++){
var emailAddress = sheet1.getRange(i,2).getValue();
var name=sheet1.getRange(i,1).getValue();
var message = sheet2.getRange(2,2).getValue();
message=message.replace("<name>",name);
MailApp.sendEmail(emailAddress, subject, message);
}
You are facing a couple hurdles here. The only way you can send a formatted email is with an HTML body. HTML is the markup language used to display a webpage in your web browser, and it can also be displayed by email clients.
So in order to send a nicely (HTML) formatted email from Apps Script, you must first generate the HTML formatted body, then you must include is using the htmlBody parameter. You should also always include a plain text body (as you are now), just incase you have a recipient who doesn't receive HTML email (common for recipients with accessibility needs, using screen readers etc.)
There is no simple way to fetch formatted text from a spreadsheet cell as HTML, so you will need to either store your raw HTML in the spreadsheet, or figure out another location you can store and fetch the HTML body from. In my example below, I hardcode both the plain text and html bodies.
To send an HTML Body with MailApp, you need to use the additional "options" parameter, as shown below.
var html_message = '<body><h1>This is an HTML formatted body</h1><br><br><strong style="color:red">This can get pretty involved.</strong> Usually you would generate this html with some other tool that lets you nicely format your content and export it as HTML.</body>'
var plain_message = 'This is a plain text email body. It is is much simpler, with no special formatting, but usually it will include all the text from the html formatted message (above), since usually you want all your recipients to receive the same information'.
MailApp.sendEmail(emailAddress, subject, plain_message, {htmlBody: html_message});
See the advanced options specification here:
https://developers.google.com/apps-script/reference/mail/mail-app#sendEmail(String,String,String,Object)

Send email html body as Base64 encoded

How do I in Mimekit send an email having the html body base64 encoded?
In code I first create the entire body as a MimeEnitity including attachments using the BodyBuilder. Then I create the MimeMessage to be sent having the body.
The first thing you'll need to do is to locate the HTML body part.
A quick hack might look something like this:
var htmlBody = message.BodyParts.OfType<TextPart> (x => x.IsHtml).FirstOrDefault ();
Then you'll need to set the Content-Transfer-Encoding:
htmlBody.ContentTransferEncoding = ContentEncoding.Base64;
That's it.

Multiple To and Cc headers in MIME message sent through LotusScript

I'm building a LotusScript agent looping through a set of documents then - based on a given condition - create mail messages with formatted html text. The recipients will be mostly Non-Notes users (Outlook etc) that's why I want to make sure that subject and message body are formatted correctly. At least one copy is sent to a Domino mail-in database, though.
The code basically creates a MimeEntity, sets "To", "CC" and "Subject" headers then puts a pre-configured message into the mail body and sends it off.
In regards to the body I experimented both with a simple MimeEntity formatted as "text/html" as well as with a multipart message (Content-Type = "multipart/alternative") with 2 child entities (1: "text/plain" without any formatting, 2: "text/html" i.e. html-formatted); in my final code I plan to go for the latter method.
What is really weird is that the recipients (using Outlook as well as other mail clients like Thunderbird) see 3 "To:" and 3 "Cc:" items instead of just one. Looking at the doc in the receiving Domino mail-in database there is only one instance of each item (i.e. SendTo and CopyTo).
Here's the message's source code (taken from Thunderbird) showing those 3 instances of each item:
Return-Path: <sendername#myorg.de>
Received: (removed info here)
Subject: =?UTF-8?B?RWluIGdlbcO8dGxpY2hlcyBzaW1wbGVzIFRlc3RtYWlsIGF1cyBTT1A=?=
MIME-Version: 1.0
Auto-Submitted: auto-generated
To: user1#orgext1.de, user2#orgext2.de
CC: my-mail-in-db#myorg.de
To: user1#orgext1.de, user2#orgext2.de
CC: my-mail-in-db#myorg.de
To: user1#orgext1.de, user2#orgext2.de
CC: my-mail-in-db#myorg.de
Message-ID: <OFBCA50979.C1582837-ONC125856E.00548385-C125856E.0054838A#MYORG.DE>
From: Lothar Mueller <sendername#myorg.de>
This the basic code creating these mails (the simple non-multipart version):
Set docMemo = db.Createdocument()
Call docMemo.Replaceitemvalue("Form", "Memo")
Set nMimeBody = docMemo.Createmimeentity()
'SendTo
Set nMimeHead = nMimeBody.Createheader("To")
Call nMimeHead.Setheaderval("user1#otherorg.de,user2#3rdorg.de")
'CopyTo
Set nMimeHead = nMimeBody.Createheader("CC")
Call nMimeHead.Setheaderval("my-mail-in-db")
'Subject
Set nMimeHead = nMimeBody.Createheader("Subject")
Call nMimeHead.Addvaltext("Subject with ä-ö-ü-ß", "UTF-8")
'html version only for simple non-multipart MIME
Call nStream.Writetext({<p style="font-weight:bold;">Some simple formatted HTML content</p>})
Call nMimeBody.Setcontentfromtext(nStream, {text/html; charset="UTF-8"}, ENC_NONE)
Call nStream.Close()
'finally send
Call docMemo.Send(False)
Now, I can work around this behavior by simply setting the recipients as plain old Notes items, like:
Call docMemo.SendTo = recipientArray
Call docMemo.CopyTo = copyArray
instead of setting those values as MIME headers. In this case there are no more multiple instances of "To" and "CC" items at the recipients' mail clients.
I know that I did this already some years ago in a different project, and back then I didn't have those problems.
Anyone having an idea what could be the cause for this? Could it be due to the Domino version in use (now it's 10.0.1 FP4, back then it was some 9.0.1 version)?
Guess I found the cause for this, at least partially:
As I mentioned in an update to my post this behavior only can be observed when the agent is running in the client as opposed to running on the server:
examining the resulting mail through Ytria's scanEZ I find that there's a difference in regards to the fields that are created:
the run-on-server version just creates the expected fields "To:" and "Cc:" which turn up as "SendTo" and "CopyTo" in the resulting Notes document
If the code is running in the client some more fields are created in the Notes document: in addition to the standard fields there are also "INetSendTo", INetCopyTo, "AltSendTo" and "AltCopyTo". I assume that those extra fields are then rendered by the router to become addition "To:" and "Cc:" header items.
Thanks again to #DaveDelay for bringing up that idea regarding the router and mail.box

How can I send a multi-part email with text/plain and text/html parts with Grails?

I've looked through the code and documentation for the Grails Mail plugin (version 0.9) and it doesn't have the support I'm looking for. You can only set a single body and then provide a mime attachment that points to a static file. I need to actual pass a model into a GSP and have it render both the HTML and plain text versions and then have those both available in the message. This will allow non-HTML-based e-mail clients to display the text/plain part and clients that support HTML to display the text/html part.
Has anybody done this with Grails? Is there an easy way to do it, or do I have to modify the mail plugin or just go to the Java Mail library directly?
Since version 1.0 the mail plugin natively supports multipart alternative content as described in http://jira.grails.org/browse/GPMAIL-37
mailService.sendMail {
multipart true
to <recipient>
subject <subject string>
text 'my plain text'
html '<html><body>my html text</body></html>'
}
We use multipart email with the standard email plugin. The following code snippet is located in a service class, that's why we're using standard groovy templating instead of the gsp engine:
Template template = groovyPagesTemplateEngine.createTemplate(<templatename>)
Writable emailBody = template.make(<data model as map>)
StringWriter bodyWriter = new StringWriter()
emailBody.writeTo(bodyWriter)
String xml = <some xml>
mailService.sendMail {
multipart true
to <recipient>
subject <subject string>
body bodyWriter
attachBytes "filename.xml", "text/xml", xml.getBytes('UTF-8')
}
The crucial thing is that 'multipart true' appears at the beginning of the closure. If you add
html '<b>Hello</b> World'
to the closure above, I assume you'll get a text and html email with an attachment.
Seems like this is potential content of version 1.0 of the Mail plugin, see this and this issue. Looking at the patch of the first issue, I think an html and text multipart message could simply be created like this:
mailService.sendMail {
multipart true
to <recipient>
subject <subject>
dualBody(template:<template>, model:<model>)
}
Would be pretty cool! No idea if / when this will be released though.

Sending email with attachment

I've a custom form (created with form API) that need send an uploaded file by email. The current form submit handler sends the email without attachment using drupal_mail().
So I'm looking for a solution to properly send email with attachment from Drupal. Mime Mail seems an overkill because HTML mail, templating and its other features are not required. But the only other alternative I see is to set the appropriate headers and serialize the attached file in the mail body when processing the mail in my hook_mail() implementation.
Did I miss anything? Is there any module to handle this?
Mimemail is the easiest solution here. Be it an overkill or not, it will allow you to get it done with a single function call.
If you insist, you may have your homemade attachment sender: base64 encode your attachment(s), add them to the mail body, add the correct headers and you're done.
You can use mime mail and force the message body to be sent in plaintext format. Here is an excerpt from the module's readme file:
USAGE
This module may be required by other modules, but is not terribly
useful by itself. Once installed, any module can send messages by
calling the mimemail() function:
$sender - a user object, text email address or an array with name, mail
$recipient - a user object, text email address or an array with name, mail
$subject - subject line
$body - body text in HTML format
$plaintext - boolean, whether to send messages in plaintext-only (default FALSE)
$headers - a keyed array with headers (optional)
$text - plaintext portion of a multipart e-mail (optional)
$attachments - array of arrays with the file's path, MIME type (optional)
$mailkey - message identifier
return - an array containing the MIME encoded message
The key thing being to set the $plaintext argument to TRUE. Now you can have your cake and eat it too.
You could always have a look at the Swift Mailer module which lets you send HTML (MIME) e-mails, e-mails with inline images and e-mails with attachments. It is also cabable of automatically generating plain text versions based on the HTML e-mail version, which in the end will let the user's e-mail client display the preferred version (HTML or plain text).
The Swift Mailer module is available on http://drupal.org/project/swiftmailer.
For the record : I'm the author and maintainer of the module.
The Webform module allows you to create a form and has a file option which can be used as an attachment. All available form components are listed on the module's manual page.
Once installed Webform will appear as a content type. Once you have saved the fundamentals, such as the title and the email to address, you will have the ability to add the required form components.
Add a component of type 'file', ensuring the 'email' (to recipient) option is ticked, and you will then be able to customize the permitted file types, extensions, sizes and upload folder.
You could use the Zend Framework.
function sendEmail($params){
ini_set('include_path', 'inc/');
require_once ('inc/Zend/Mail.php');
$mail = new Zend_Mail();
$mail->setSubject( $params['subject'] );
$mail->setBodyText( $params['bodyText'] );
$mail->setBodyHtml( $params['bodyHtml'] );
$mail->setFrom( $params['fromEmail'], $params['fromName'] );
$mail->addTo( $params['toEmail'], $params['toName'] );
// Finally, add an attachment
assert( file_exists($params['attachFile']) );
$at = $mail->addAttachment(file_get_contents($params['attachFile']));
$at->type = $params['attachType'];
$at->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
$at->filename = $params['attachName'];
$mail->send();
}