Display emails before sending with Javascript - javascript

I am trying to create a script that will open the default email client, fill in certain variables but still allow the user to make changes and send. Right now my script will send the email (email.send) but I am looking for a way for the email to be displayed rather than sent. Here is the code:
var email = new Email()
email.subject = item.PO_ID
email.to = [item.BUYER_EMAIL, "accounting#test.com", "user#test.com"]
email.body = "Test body"
email.send()
What do I change .send() to?

Untested, but have you tried using using window.location() and sending the browser to something like:
mailto:accounting#test.com?subject=Test&body=Test Body
Replacing the email, subject and body using JS.

Related

Sending email via GmailApp as HTML to retain signature & image

I have a project where i need to bulk send an email with text specific to each user, and with the signature and image from the associated gmail account. I've got this atm:
//get template/draft email & body
const scGmailTemplate = GmailApp.getDraft("r4329894329375089160");
const scGmailTemplateMessage = scGmailTemplate.getMessage();
const scGmailTemplateBody = scGmailTemplateMessage.getBody();
//create new gmail
let scGmailContactMessageBody = scGmailTemplateBody;
//create array for gmail find & replaces [find, replace]
const gmailFindReplace = [["INV_START", scVars.INV_START],
["INV_END", scVars.INV_END],
["DEM_DATE", scVars.DEM_DATE]
];
gmailFindReplace.forEach(x=>{scGmailContactMessageBody=scGmailContactMessageBody.replace(x[0], x[1])});
const scGmailSubject = "Service Charge Invoice ("+scVars.INV_START+"-"+scVars.INV_END+")";
let bodyHtml = HtmlService.createHtmlOutput(scGmailContactMessageBody);//didnt work
GmailApp.sendEmail("me#me.com", "test", scGmailContactMessageBody);
Issue is the resultant email is just the raw html with the image displayed at the bottom
I've tried adding {htmlBody: html} as an option but that throws an error html not defined.
Any help would be much appreciated
The htmlBody expects a string.
GmailApp.sendEmail("me#me.com", "test", scGmailContactMessageBody, {htmlBody: scGmailContactMessageBody});
No need for let bodyHtml = HtmlService.createHtmlOutput(scGmailContactMessageBody); as getBody() already returns an HTML string.
From the question
I've tried adding {htmlBody: html} as an option but that throws an error html not defined.
The error message is straight forward, the code doesn't include an statement declaring html
try replacing html by bodyHtml

Sending an email in HTML and plain with a Gmail Apps Script

I'm writing an auto-replying bot for gmail using Google Apps Script (http://script.google.com). Each time I use GmailThread's Reply to reply to message:
var htmlbody = "Hello<br>This is a <b>test</b>.<br>Bye.";
var body = "Hello,\nThis is a test.\nBye.";
thread.reply(body, {htmlBody: htmlbody, from: "Myself <hello#example.com>"});
I need to write the message both in plain text body and HTML in htmlbody.
Would there be a way to write an email only in HTML (to avoid writing every email content twice, plain and HTML!), and let reply() automatically send the email both in HTML and plaintext version?
I tried
var body = htmlbody.replace(/<br>/g,'\n').replace(/<b>/g,'');
// we should also replace </b> by '', etc.
but this is a bit of a hack. Is there a better version?
Google Scripts cannot generate the plain text portion automatically but you write a simple regex based replaces that removes all the tags from the HTML for plain text.
var body = htmlBody.replace(/<.+?>/g, "");
thread.reply(body, {htmlBody: htmlbody, from: "Myself <hello#example.com>"});
Also, if you set the body to blank, most modern email clients would still be able to render the image.

Send Form with MailApp after fetching html. Embed Google Form into email. Generated email contains only text

I want to embed a Google form in an email and send it with MailApp. I'm attempting to use code found at: https://stackoverflow.com/a/23671529/4305236:
var form = FormApp.create('New Form');
....
var url = form.getPublishedUrl();
var response = UrlFetchApp.fetch(url);
var htmlBody = HtmlService.createHtmlOutput(response).getContent();
MailApp.sendEmail({
to: email,
subject: subject,
htmlBody: htmlBody,
});
...
The logs show all the html for the form.
However, when I run the code, the email just looks like text, with the links at bottom. When I "show original" in the email, though, all that html for the form seems to be there, like in the log...
Would greatly appreciate any help.
What generated form looks like, want this to be embedded in email:
What they are getting instead:
Answered here: https://stackoverflow.com/a/60749897/3383907.
Copy/pasting for history purposes:
When Google sends the form to folks directly and embeds the form in the email they are using their new offering called AMP. You can read more about it here:
https://developers.google.com/amp/
https://www.blog.google/products/g-suite/bringing-power-amp-gmail/
https://developers.google.com/gmail/ampemail/
The code you're using gets the raw HTML of the form as it would be rendered for a user in a browser. This code is not in AMP format. Ergo it will not do what you want.
If you want that AMP experience you will need to create the AMP email yourself.
I don't think FormApp has a programatic way to send the form to folks, like you can from https://docs.google.com/forms/.
I hope that helps.

How send mail using JS? [duplicate]

This is a little confusing to explain, so bear with me here...
I want to set up a system where a user can send templated emails via my website, except it's not actually sent using my server - it instead just opens up their own local mail client with an email ready to go. The application would fill out the body of the email with predefined variables, to save the user having to type it themselves. They can then edit the message as desired, should it not exactly suit their purposes.
There's a number of reasons I want it to go via the user's local mail client, so getting the server to send the email is not an option: it has to be 100% client-side.
I already have a mostly-working solution running, and I'll post the details of that as an answer, I'm wondering if there's any better way?
The way I'm doing it now is basically like this:
The HTML:
<textarea id="myText">
Lorem ipsum...
</textarea>
<button onclick="sendMail(); return false">Send</button>
The Javascript:
function sendMail() {
var link = "mailto:me#example.com"
+ "?cc=myCCaddress#example.com"
+ "&subject=" + encodeURIComponent("This is my subject")
+ "&body=" + encodeURIComponent(document.getElementById('myText').value)
;
window.location.href = link;
}
This, surprisingly, works rather well. The only problem is that if the body is particularly long (somewhere over 2000 characters), then it just opens a new email but there's no information in it. I suspect that it'd be to do with the maximum length of the URL being exceeded.
Here's the way doing it using jQuery and an "element" to click on :
$('#element').click(function(){
$(location).attr('href', 'mailto:?subject='
+ encodeURIComponent("This is my subject")
+ "&body="
+ encodeURIComponent("This is my body")
);
});
Then, you can get your contents either by feeding it from input fields (ie. using $('#input1').val() or by a server side script with $.get('...'). Have fun
You don't need any javascript, you just need your href to be coded like this:
email me here!
You can use this free service: https://www.smtpjs.com
Include the script:
<script src="https://smtpjs.com/v2/smtp.js"></script>
Send an email using:
Email.send(
"from#you.com",
"to#them.com",
"This is a subject",
"this is the body",
"smtp.yourisp.com",
"username",
"password"
);
What about having a live validation on the textbox, and once it goes over 2000 (or whatever the maximum threshold is) then display 'This email is too long to be completed in the browser, please <span class="launchEmailClientLink">launch what you have in your email client</span>'
To which I'd have
.launchEmailClientLink {
cursor: pointer;
color: #00F;
}
and jQuery this into your onDomReady
$('.launchEmailClientLink').bind('click',sendMail);
If this is just going to open up the user's client to send the email, why not let them compose it there as well. You lose the ability to track what they are sending, but if that's not important, then just collect the addresses and subject and pop up the client to let the user fill in the body.
The problem with the very idea is that the user has to have an email client, which is not the case if he rely on webmails, which is the case for many users. (at least there was no turn-around to redirect to this webmail when I investigated the issue a dozen years ago).
That's why the normal solution is to rely on php mail() for sending emails (server-side, then).
But if nowadays "email client" is always set, automatically, potentially to a webmail client, I'll be happy to know.
Send request to mandrillapp.com:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
}
}
xhttp.open('GET', 'https://mandrillapp.com/api/1.0/messages/send.json?message[from_email]=mail#7995.by&message[to][0][email]=zdanevich.vitaly#yaa.ru&message[subject]=Заявка%20с%207995.by&message[html]=xxxxxx&key=oxddROOvCpKCp6InvVDqiGw', true);
xhttp.send();
You can add the following to the <head> of your HTML file:
<script src="https://smtpjs.com/v3/smtp.js"></script>
<script type="text/javascript">
function sendEmail() {
Email.send({
SecureToken: "security token of your smtp",
To: "someone#gmail.com",
From: "someone#gmail.com",
Subject: "Subject...",
Body: document.getElementById('text').value
}).then(
message => alert("mail sent successfully")
);
}
</script>
and below is the HMTL part:
<textarea id="text">write text here...</textarea>
<input type="button" value="Send Email" onclick="sendEmail()">
So the sendEmail() function gets the inputs using:
document.getElementById('id_of_the_element').value
For example, you can add another HTML element such as the subject (with id="subject"):
<textarea id="subject">write text here...</textarea>
and get its value in the sendEmail() function:
Subject: document.getElementById('subject').value
And you are done!
Note: If you do not have a SMTP server you can create one for free here. And then encrypt your SMTP credentials here (the SecureToken attribute in sendEmail() corresponds to the encrypted credentials generated there).

Calling: GetRespondentEmail Specific

The following code is used to send an email to the respondent of a google form. The onsubmit call is from the spreadsheet that stores the responses.
I am not sure how to get the forms ID to use the solution given in several other places. Basically I just need to know how to call the getRespondentEmail(). I've tried calling it using FormApp.getActive() but I read that only works when you are working in the form it's self.
If you want to offer a solution that requires using the form ID, an explanation of how to get the ID would be great.
var GetUserEmail = getRespondentEmail().
var subject = "Skiver Production Report Successfully Submitted";
var textbody = "You have successfully submitted a Skiver Production Report. Do not reply to this email as it is not monitored.";
var message = "You have succesfully submitted a Skiver Production Report. Do not reply to this email as it is unmoinitored." ;
var cc = "techlab#worldwidefoam.com";
var sendername = "Quality Function";
GmailApp.sendEmail("bob#notArealemail.com", subject, textbody, {
cc: cc,
name: sendername,
htmlBody: message
});
To get the id of an element you can simply use the document.getElementById(arg) method. For example:
var myForm = document.getElementById("ID");
For simply calling getRespondentEmail you just place getRespondentEmail() in your code. Your first line is doing this correctly but the . at the end needs to be removed or replaced with a ;, which is likely causing your error:
var GetUserEmail = getRespondentEmail(); // replace . with ;
Lastly if you would like to use getRespondentEmail() anywhere make sure it is in a global scope. Meaning it's not defined in any functions or closures.

Categories