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

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)

Related

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.

Chilkat - Duplicate attachment

I've an EML file with ONE attachment, but when I load it with the Chilkat email component, the values for numOfAttachments AND NumRelatedItems are both 1.
The attachment is a PDF file.
Why is the PDF file also a related item? How can I ensure, that the PDF file will be only processed one time.
Example:
var email = new Chilkat.Email();
email.LoadEml("myEmlFile.eml");
for (int i = 0; i < email.NumAttachments; i++) {
// ... do something
}
for (int i = 0; i < email.NumRelatedItems; i++) {
// ... do something
}
Thanks
Best regards
Sebastian
In some cases, it is possible that an item is both a related item and an attachment. The semantics of it can point both ways. Examine the .eml in a text editor to see what you have. Where is the PDF located in the nested MIME structure? If, for example, it was directly under the multipart/mixed MIME part, then it would certainly be only an attachment. If, however, the PDF was located under the multipart/related, then it would be a related item -- especially if the content-disposition is inline. But most people expect the PDF to be an attachment.
In other words, the email may be such that the PDF is located under multipart/related with an "inline" disposition, but some programmers expect it to be a related item, whereas others expect it to be an attachment. There's no single solution for everybody..

How can I distinguish between attachment types in exchangelib?

I've just noticed that Microsoft OWA does not display some attachments. Some people use images in their footer (which are attachments). I'm not sure if the only difference between a "normal" attachment and this emedded attachment is that it is embedded in the email.
Is there another difference? How can I get only attachments which OWA* displays as attachements?
* and probably most other email clients; I think I've seen a similar behavior in Google Mail
Those attachments have a content_id. They are referenced within the mail.body as cid:[CONTENT-ID]. The content_id looks like this:
cid:image001.jpg#01D3151A.F9036A80
where image001.jpg is the filename.
looking for cid:image_name inside mail body fails for embedded images with src referring to a link rather than cid.
so the best solution would be to use attachments.is_inline property which is built in exchangelib.
for attachment in msg.attachments:
if msg.has_attachments == True:
if isinstance(attachment, FileAttachment):
if attachment.is_inline:
print("Embeded Image")
else:
print("Normal Attachment")
reference: https://github.com/ecederstrand/exchangelib/issues/562

Attach a file to a mail and send it

I have the following code, which tries to send a mail with a .pdf file attached. This .pdf is located in my Google drive.
var files = DriveApp.getFilesByName('file_test.pdf');
GmailApp.sendEmail(email, subject, message, {attachments:files[0]});
I've found that "getFilesByName" returns an array, so that's why I'm using files[0], but it's still not working. I don't know how to debug it, so when I'm testing my code, I am able to send the mail, but I receive it with no attached files.
When you use getFilesByName you are receiving a FileIterator, so you should use the hasNext() and next() functions to retrieve your file.
var files = DriveApp.getFilesByName('file_test.pdf');
if(files.hasNext()){
var file = files.next();
GmailApp.sendEmail(email, subject, message, {attachments:file});
}
In the GmailApp docs, they use the getAs() function on the file to return it as a PDF, this may or may not be necessary in your case.
See:
https://developers.google.com/apps-script/reference/gmail/gmail-app#sendEmail(String,String,String,Object)
https://developers.google.com/apps-script/reference/drive/drive-app

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