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

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.

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.

Nancy - return pdf stream via ajax

Is there any sample out there how to return a pdf stream (e.g. generated by Crystal Report) from a nancy module via an ajax request?
I'm not sure what you mean by "ajax request" and why it matters, but recently we had to solve similar problem - i.e. returning pdf, generated from other tool. We ended up using as a template a binary processor, utilizing the content negotiation.
You can modify the binary processor to work with application/pdf MIME type and "pdf" file extensions, so it returns the proper response whenever the request has an Accept header of "application/pdf" or when the request is like http://example.com/reports/report.pdf.
Using this, and assuming you have IReportEngine with Stream GetReportByName(string name), your module will look like (pseudo code):
Get["reports/{reportName}"] = _ => _engine.GetReportByName(_.reportName);

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();
}

Sending an HTML email using Swift

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');.