I am facing an issue where all of my text e-mails are scrunched together and do not have new lines persisting through the sending process.
Here is the code:
def send_ses_message(email_to, subject, body):
ses = init_ses_internal()
if ses:
ses.send_email(
Source='no-reply#domain.com',
Destination={
'ToAddresses': [
email_to,
],
},
Message={
'Subject': {
'Data': subject,
},
'Body': {
'Text': {
'Data': body,
'Charset': 'UTF-8',
},
'Html': {
'Data': body,
'Charset': 'UTF-8',
},
}
},
ReplyToAddresses=[
'mharris#domain.com', # just in case someone replies to a no-reply# address I'll receive them
],
ReturnPath='mharris#domain.com', # bounce backs will come to me also
)
return True
I have most recently tried forcing UTF-8 hoping that would allow the newlines to persist. After that I added \n where a new line should exist.
Here is an example of a email:
def send_reset_email(self, email_to, unique_id):
subject = "Company Password Reset"
body = """
Hello!\n\n
We have received a request to reset your password.\n
Please click the link below to proceed with resetting your password. Note: this link will expire in 1 hour.\n\n
http://staging.domain.com/password/reset/{}\n\n
If you did not request this reset you can safely ignore this e-mail.\n\n
Thank you for choosing Company!\n\n
The Company Team\n
www.company.com\n
""".format(unique_id)
send_ses_message(email_to, subject, body)
Please let me know what I can do to ensure that newlines are persistent across Amazon SES. Thanks!
The default content type in SES seems to be text/html, so using <br> instead of \n worked for me
Edit: I was having a similar issue with outlook 2013 clients. Adding a tab character before the newline worked for me.
Replacing \n with \t\n
Or \t\r\n
How do I format a String in an email so Outlook will print the line breaks?
I faced similar issue in sending a contents of log file (stored in variable) to HTML BODY.
Replacing the new line with "<br />" as below helped solve the problem. Below command replaces all newline characters in the text with "<br />".
mytext = mytext.split("\n").join("<br />")
Related
I have a validated domain, and sending a direct email via the AWS Pinpoint console works fine. However, I can't get the same to work with Boto3 send_messages.
I get {'DeliveryStatus': 'PERMANENT_FAILURE', 'StatusCode': 400, 'StatusMessage': 'Request must include message email message.'}
But I have a MessageConfiguration Default Message with a simple string for Body, and I've tried BodyOverride as well. No problems sending SMS.
I've been unable to snag an example of send_messages, and I think if I saw a working example of an email send, that'd be all I need.
Snippet:
response = ppClient.send_messages(
ApplicationId=pinpointId,
MessageRequest={
'Addresses': {
'mguard#{validateddomain}.com': {
# 'BodyOverride': 'Hello from Pinpoint!',
'ChannelType': 'EMAIL',
}
},
'MessageConfiguration': {
'DefaultMessage': {
'Body': 'Default Message for EMAIL.',
'Substitutions': {}
}
}
}
)
I am trying to send mail with a PDF attachment using Mailjet from Google Apps Script. I can send regular mail without issue, but not quite sure how to include an attachment.
Mailjet documentation: https://dev.mailjet.com/guides/#sending-with-attached-files
I think my problem is the Base64Content. I don't really understand how to encode the attachment. When I execute the below code, an email is being sent with a PDF attachment, but when I try and open the PDF it displays: "Cannot display PDF (test.pdf is of invalid format)".
var newDoc = DocumentApp.openById(newDocid)
var attachment = newDoc.getAs(MimeType.PDF);
var mailjeturl = "https://api.mailjet.com/v3.1/send";
var mailjetparams = {
"Messages":[{
"From": {"Email": 'myemail#domain.com',"Name": 'Robert'},
"To": [{"Email": 'theiremail#domain.com'}],
"Subject": 'subject',
"HTMLPart": 'this message',
"Attachments": [{"ContentType": "application/pdf",
"Filename": "test.pdf",
"Base64Content": Utilities.base64Encode(attachment)}]
}]
}
var mailjetoptions = {
'method': 'post',
'contentType': 'application/json',
'payload': JSON.stringify(mailjetparams),
'headers': {'Authorization': 'Basic ' + Utilities.base64Encode(MAILJET_KEY)}
};
var response = JSON.parse(UrlFetchApp.fetch(mailjeturl, mailjetoptions))
Try to encode like this:
var pdf = newDoc.getAs('application/pdf').getBytes();
var attach = {fileName:'test.pdf',content:pdf, mimeType:'application/pdf'};
var mailjetparams = {
"Messages":[{
"From": {"Email": 'sender#domain.com',"Name": 'Robert'},
"To": [{"Email": 'reciever#domain.com'}],
"Subject": 'subject',
"HTMLPart": 'this message',
"Attachments": [attach]
}]
}
How about the following modification? I thought that the reason of the error may be Utilities.base64Encode(attachment).
Modification points :
attachment retrieved by newDoc.getAs(MimeType.PDF) is Blob. The Blob cannot be directly converted to base64 using Utilities.base64Encode(). So please convert Blob to byte array, and convert to base64.
When this is reflected to your script. The modification part is as follows.
From :
var attachment = newDoc.getAs(MimeType.PDF);
To :
var attachment = newDoc.getAs(MimeType.PDF).getBytes();
or
var attachment = newDoc.getBlob().getBytes();
When Google Document is retrieved as a Blob, Google converts automatically to PDF. You can also use this.
Reference :
base64Encode()
If I misunderstand your question, I'm sorry.
I want to send an email using a template. I want to have a GSP file where i could style it, and send the email. Currently the send mail function is as follows:
def sendEmail(){
mailService.sendMail {
to "email","**email**"
from "email"
subject "Hi"
body 'Hi'
}
}
in my config.groovy file
grails {
mail {
host = "smtp.gmail.com"
port = 465
username = "email"
password = "pwd"
props = ["mail.smtp.auth":"true",
"mail.smtp.socketFactory.port":"465",
"mail.smtp.socketFactory.class":"javax.net.ssl.SSLSocketFactory",
"mail.smtp.socketFactory.fallback":"false"]
}
}
I went through another Stack Overflow post on this: Where should i add the mail templates ? is it in the views folder ?
sendMail{
multipart true
to "[hidden email]"
subject "Subject goes here"
html g.render( template: '/emails/mailTemplate')
inline 'springsourceInlineImage', 'image/jpg', new File('./web-app/images/springsource.png')
}
UPDATE
I TREID ADDING A mailTemplate.gsp UNDER EMAILS/ BUT IT DIDNT WORK.
ERROR I GOT Template not found for name [/emails/mailTemplate] and path [/emails/_mailTemplate.gsp]
You can use groovyPageRenderer.render() to parse your email. Below, an example:
class MailingService {
def groovyPageRenderer
def mailService
def yourFunction(User user) {
def content = groovyPageRenderer.render(view: '/mails/myTemplate')
mailService.sendMail {
to user.email
from "email#test.com"
subject "MySubject"
html(content)
}
}
}
In this case, the template is here: /views/mails/MyTemplateFile.gsp
Hope this helps.
Edit:
And the render could be used with a model. Example:
groovyPageRenderer.render(view:'/mails/myTemplate',model:[user:user])
Edit2:
I forgot to add the mailService in my first reply
well, you can try this code...
mailService.sendMail {
to user.email
from "email#test.com"
subject "MySubject"
body(view:'/emails/mailTemplate', model: [a:A])
}
here mailTemplate.gsp is in view/emails. In body of mail service you can use render syntax.
then add '<%# page contentType="text/html" %>' in top of mailTemplate.gsp
Well looking at your code, everything looks good enough.
html g.render(template : '/path/to/template')
should render your template and it will become the body of your mail message.
Have you made sure that you made your template as _template. Since all the gsp's that start with (_) are only considered as a template.
You should also make all the styling(css) inline so that it gets rendered without errors in all mail providers.
I'm having some difficulty implementing paypal implicit payments and unfortunately there is very limited details in the error message response from paypal.
Here's the request:
{
"actionType": "PAY",
"currencyCode": "USD",
"cancelUrl": "http://my_domain.com/cancel_url",
"returnUrl": "http://my_domain.com/return_url",
"requestEnvelope.errorLanguage": "en_US",
"requestEnvelope.detailLevel": "ReturnAll",
"senderEmail": "sender#email.com",
"receiverList.receiver(0).amount": 50,
"receiverList.receiver(0).email": "receiver#email.com"
}
Here's the headers i'm setting:
"Content-Type", "application/json"
"Accept-Language", "en_US"
"X-PAYPAL-SECURITY-USERID", "username"
"X-PAYPAL-SECURITY-PASSWORD", "pwd"
"X-PAYPAL-SECURITY-SIGNATURE", "sig"
"X-PAYPAL-APPLICATION-ID", "My App id"
"X-PAYPAL-REQUEST-DATA-FORMAT", "JSON"
"X-PAYPAL-RESPONSE-DATA-FORMAT", "JSON"
Here's the response:
{
"responseEnvelope":{
"timestamp":"2013-04-06T12:02:41.011-07:00",
"ack":"Failure",
"correlationId":"3842d361b077d",
"build":"5563463"},"error":[{
"errorId":"580001",
"domain":"PLATFORM",
"subdomain":"Application",
"severity":"Error",
"category":"Application",
"message":"Invalid request: {0}"
}]
}
I just had the exact same problem and couldn't find the answer anywhere. Turns out I was using a GET request instead of POST. It's odd though that the errorId 580001 is nowhere to be found in their docs.
The adaptive payments API doesn't accept whitespace in the request payload, remove all the spaces and newlines and give it another try. Took me ages to figure that out.
Another thing to look out for is encoding. I've had this error and realised that it was due to an ampersand in the "memo" field. If you send the request as NVP be sure to URL encode where possible.
let payload={
"actionType":"PAY",
"currencyCode":"USD",
"receiverList":{
"receiver":[{
"amount":1.00,
"email":"buyer email"
}]
},
"returnUrl":"succes url",
"cancelUrl":"cancel url",
"requestEnvelope":{
"errorLanguage":"en_US",
"detailLevel":"ReturnAll"
}
}
let url = "https://svcs.sandbox.paypal.com/AdaptivePayments/Pay";
return this.http.post(url, payload, { headers: headers })
headers.append('X-PAYPAL-SECURITY-USERID', 'security id');
headers.append('X-PAYPAL-SECURITY-PASSWORD', 'password');
headers.append('X-PAYPAL-SECURITY-SIGNATURE', 'signature');
headers.append('X-PAYPAL-REQUEST-DATA-FORMAT', 'JSON');
headers.append('X-PAYPAL-RESPONSE-DATA-FORMAT', 'JSON');
headers.append('X-PAYPAL-APPLICATION-ID', 'APP-id');
As another cause of this issue, make sure the amount property for each receiver does not contain a comma, as this will also break. I.e. 1000.00 instead of 1,000.00.
Is there any library for NodeJS for sending mails with attachment?
Yes, it is pretty simple,
I use nodemailer: npm install nodemailer --save
var mailer = require('nodemailer');
mailer.SMTP = {
host: 'host.com',
port:587,
use_authentication: true,
user: 'you#example.com',
pass: 'xxxxxx'
};
Then read a file and send an email :
fs.readFile("./attachment.txt", function (err, data) {
mailer.send_mail({
sender: 'sender#sender.com',
to: 'dest#dest.com',
subject: 'Attachment!',
body: 'mail content...',
attachments: [{'filename': 'attachment.txt', 'content': data}]
}), function(err, success) {
if (err) {
// Handle error
}
}
});
Try with nodemailer, for example try this:
var nodemailer = require('nodemailer');
nodemailer.SMTP = {
host: 'mail.yourmail.com',
port: 25,
use_authentication: true,
user: 'info#youdomain.com',
pass: 'somepasswd'
};
var message = {
sender: "sender#domain.com",
to:'somemail#somedomain.com',
subject: '',
html: '<h1>test</h1>',
attachments: [
{
filename: "somepicture.jpg",
contents: new Buffer(data, 'base64'),
cid: cid
}
]
};
finally, send the message
nodemailer.send_mail(message,
function(err) {
if (!err) {
console.log('Email send ...');
} else console.log(sys.inspect(err));
});
Personally i use Amazon SES rest API or Sendgrid rest API which is the most consistent way to do it.
If you need a low level approach use https://github.com/Marak/node_mailer and set up your own smtp server (or one you have access too)
http://blog.nodejitsu.com/sending-emails-in-node
Have you tried Nodemailer?
Nodemailer supports
Unicode to use any characters
HTML contents as well as plain text alternative
Attachments
Embedded images in HTML
SSL (but not STARTTLS)
You may use nodejs-phpmailer
You can also use AwsSum's Amazon SES library:
https://github.com/appsattic/node-awssum/
In there, there is an operation called SendEmail and SendRawEmail, the latter of which can send attachments via the service.
use mailer package it is very flexible and easy.
Another alternative library to try is emailjs.
I gave some of the suggestions here a try myself but running code complained that send_mail() and sendMail() is undefined (even though I simply copy & pasted code with minor tweaks). I'm using node 0.12.4 and npm 2.10.1. I had no issues with emailjs, that just worked off the shelf for me. And it has nice wrapper around attachments, so you can attach it various ways to your liking and easily, compared to the nodemailer examples here.
Nodemailer for any nodejs mail needs. It's just the best at the moment :D
I haven't used it but nodemailer(npm install nodemailer) looks like what you want.
Send With express-mailer (https://www.npmjs.com/package/express-mailer)
Send PDF -->
var pdf="data:application/pdf;base64,JVBERi0xLjM..etc"
attachments: [ { filename: 'archive.pdf',
contents: new Buffer(pdf.replace(/^data:application\/(pdf);base64,/,''), 'base64')
}
]
Send Image -->
var img = 'data:image/jpeg;base64,/9j/4AAQ...etc'
attachments: [
{
filename: 'myImage.jpg',
contents: new Buffer(img.replace(/^data:image\/(png|gif|jpeg);base64,/,''), 'base64')
}
]
Send txt -->
attachments: [
{
filename: 'Hello.txt',
contents: 'hello world!'
}
]
you can use official api of google for this.
They have provided package for node for this purpose.
google official api
Ive attached part of my code that did the attachment thing for me
function makeBody(subject, message) {
var boundary = "__myapp__";
var nl = "\n";
var attach = new Buffer(fs.readFileSync(__dirname + "/../"+fileName)) .toString("base64");
// console.dir(attach);
var str = [
"MIME-Version: 1.0",
"Content-Transfer-Encoding: 7bit",
"to: " + receiverId,
"subject: " + subject,
"Content-Type: multipart/alternate; boundary=" + boundary + nl,
"--" + boundary,
"Content-Type: text/plain; charset=UTF-8",
"Content-Transfer-Encoding: 7bit" + nl,
message+ nl,
"--" + boundary,
"--" + boundary,
"Content-Type: Application/pdf; name=myPdf.pdf",
'Content-Disposition: attachment; filename=myPdf.pdf',
"Content-Transfer-Encoding: base64" + nl,
attach,
"--" + boundary + "--"
].join("\n");
var encodedMail = new Buffer(str).toString("base64").replace(/\+/g, '-').replace(/\//g, '_');
return encodedMail;
}
P.S thanks to himanshu for his intense research on this
The answer is not updated with the last version of nodemailer#6.x
Here an updated example:
const fs = require('fs')
const path = require('path')
const nodemailer = require('nodemailer')
const transport = nodemailer.createTransport({
host: 'smtp.libero.it',
port: 465,
secure: true,
auth: {
user: 'email#libero.it',
pass: 'HelloWorld'
}
})
fs.readFile(path.join(__dirname, 'test22.csv'), function (err, data) {
transport.sendMail({
from: 'email_from#libero.it',
to: 'email_to#libero.it',
subject: 'Attachment',
text: 'mail content...', // or body: field
attachments: [{ filename: 'attachment.txt', content: data }]
}, function (err, success) {
if (err) {
// Handle error
console.log(err)
return
}
console.log({ success })
})
})