Cant send a message using Gmail API in browser - api

I am trying to send email using Gmail API in my browser app. My function looks like:
function sendMessage(recepient, message, done) {
var base64EncodedEmail = '';
var request = gmail.users.messages.send({
to: recepient,
userId: 'me',
resource: {
raw: base64EncodedEmail
}
});
request.execute(done);
}
I am getting the following:
'raw' RFC822 payload message string or uploading message via /upload/* URL required
What am I doing wrong here?

Figured out ... thanks to Google REST API - message in an RFC 2822 formatted and base64url encoded string. The new function is
function sendMessage(recepient, subject, message, done) {
var base64EncodedEmail = btoa(`From: me\r\nTo: ${recepient}\r\nSubject: ${subject}\r\n\r\n${message}`)
.replace(/[\/\+]/g, '_')
.replace(/=+$/, '');
var request = gmail.users.messages.send({
userId: 'me',
resource: { raw: base64EncodedEmail }
});
request.execute(done);
}

Related

how to send parameters in future class

i want to consume a web service that require headers, body and parameters in future class
but the problem it shows an error "the named parameters isn't defined'
Future<http.Response> postLogin(String login, String password, String jwt) async{
final response = await http.post(Uri.encodeFull('$baseurl/mobile/login'),
headers: {
HttpHeaders.acceptHeader: 'application/json ; charset=utf-8',
HttpHeaders.contentTypeHeader:'application/x-www-form-urlencoded',
HttpHeaders.authorizationHeader :'Bearer $jwt',
},
body: bodyLoginToJson(login, password, token),
parameters: {
token, login
}
);
can someone help please
As mentioned by #jamesdlin, parameters is not a named parameter of the http class. The standard way of posting values using dart / flutter is a map past to the body parameter. Don't assume the terminology used in postman will be the same in dart.
Map<String, String> _headers = {
"Accept":"application/json"
};
var response = await http.post(LOGIN_URL, headers: _headers, body: {
"username": username,
"password": password,
// whatever other key values you want to post.
}).then((dynamic res) {
// ... Do something with the result.
});

Nodemailer attachment not working in nodemailer 0.7.1

I am trying to send an attachment using nodemailer 0.7.1. The attachment is sent fine but when I try to open it, the shows ERROR OPENING FILE.
Here is my code:
var nodemailer = require("nodemailer");
var transport = nodemailer.createTransport("SMTP", {
host: "smtp.gmail.com", // hostname
secureConnection: true, // use SSL
port: <port>, // port for secure SMTP
auth: {
user: "example.example#gmail.com",
pass: "password"
}
});
console.log("SMTP Configured");
var mailOptions = {
from: 'example.sender#gmail.com', // sender address
to: 'example.receiver#gmail.com', // list of receivers
subject: 'Report for Test Result', // Subject line
text: 'Contains the test result for the test run in html file', // plaintext body
attachments: [
{
'filename': 'results.txt',
'filePath': './result/results.txt',
}
]
};
transport.sendMail(mailOptions, function (error, response) {
if (error) {
console.log(error);
} else {
console.log("Message sent: " + response.message);
}
});
Any suggestion on how to resolve this would be of great help.
Replace the filename and filePath lines with path: './result/results.txt' and try.
Try this code.First you have to create an app in Google Cloud Console and Enable Gmail API from library.Get the credentials of your app.For that click on Credentials and in the place of Authorized redirect URIskeep this link https://developers.google.com/oauthplayground and save it.Next in another tab open this link https://developers.google.com/oauthplayground/ click on settings symbol on right side.And make a tick on check box(i.e,Use your own OAuth credentials) after this You have to give your clientId and clientSecret.And at the sametime on left side there is a text box with placeholder like Input Your Own Scopes there keep this link https://mail.google.com/ and click on Authorize APIs then click on Exchange authorization code for tokens then you will get your refreshToken and accessToken keep these two in your code.Hope thsi helps for you..
const nodemailer=require('nodemailer');
const xoauth2=require('xoauth2');
var fs=require('fs');
var transporter=nodemailer.createTransport({
service:'gmail',
auth:{
type: 'OAuth2',
user:'Sender Mail',
clientId:'Your_clientId',//get from Google Cloud Console
clientSecret:'Your clientSecret',//get from Google Cloud Console
refreshToken:'Your refreshToken',//get from https://developers.google.com/oauthplayground
accessToken:'Tor accessToken'//get from https://developers.google.com/oauthplayground
},
});
fs.readFile("filePath",function(err,data){
var mailOptions={
from:' <Sender mail>',
to:'receiver mail',
subject:'Sample mail',
text:'Hello!!!!!!!!!!!!!',
attachments:[
{
'filename':'filename.extension',//metion the filename with extension
'content': data,
'contentType':'application/type'//type indicates file type like pdf,jpg,...
}]
}
transporter.sendMail(mailOptions,function(err,res){
if(err){
console.log('Error');
}
else{
console.log('Email Sent');
}
})
});

Sending Templated emails with node.js, node mailer and nodemailer-mailgun-transport

I have the following basic nodejs app:
var nodemailer = require('nodemailer');
var hbs = require('nodemailer-express-handlebars');
var options = {
viewEngine: {
extname: '.hbs',
layoutsDir: 'views/email/',
defaultLayout : 'template',
partialsDir : 'views/partials/'
},
viewPath: 'views/email/',
extName: '.hbs'
};
var mg = require('nodemailer-mailgun-transport');
var auth = {
auth: {
api_key: ' mailgun api key ',
domain: ' mailgun email domain '
}
}
var mailer = nodemailer.createTransport(mg(auth));
mailer.use('compile', hbs(options));
mailer.sendMail({
from: 'test#inventori.io',
to: 'test#test.com',
subject: 'Any Subject',
template: 'email.body',
context: {
variable1 : 'value1',
variable2 : 'value2'
}
}, function (error, response) {
// console.error(error);
if (error) {
throw error;
};
console.log('mail sent to ',response);
mailer.close();
});
views/email/template.hbs
{{>email/head}}
<body>
{{>email/header}}
{{{body}}}
{{>email/footer}}
</body>
</html>
views/email/email.body.hbs
<h4>Main Body Here</h4>
{{variable1}} <br/>
{{variable2}}
views/partials/email/header.hbs
<h4>Header Content</h4>
views/partials/email/footer.hbs
<h4>Footer Content</h4>
The handlebars template engine gives zero errors but the mailgun transport throws the following error:
Error: Sorry: template parameter is not supported yet. Check back soon!
at IncomingMessage.<anonymous> (~/test/node_modules/nodemailer-mailgun-transport/node_modules/mailgun-js/lib/request.js:228:15)
at IncomingMessage.emit (events.js:129:20)
at _stream_readable.js:908:16
at process._tickCallback (node.js:355:11)
This example uses the gmail node mailer transport:
http://excellencenodejsblog.com/express-nodemailer-sending-mails/
I would like to be able to send templated emails using mailgun.
Any help would be greatly appreciated.
Thank you.
Change your template parameter to html.
If you look at the source code here, the error correct- there is no such thing as a template parameter.
For me, templates weren't rendering properly because I was following an example using extName when the key was actually extname (all lowercase). Perhaps it was renamed overtime and the guide I was looking at is now somewhat out of date.
Full working example below as of 30 May 2020.
Directory Structure:
root/
src/
email-templates/
layouts/
blank.hbs
partials/
hello.hbs
services/
email.service.ts
email.service.ts (Haven't updated this to use proper types yet. Just a poc.)
export async function sendTestEmail() {
try {
// Generate test SMTP service account from ethereal.email
// Only needed if you don't have a real mail account for testing
const testAccount = await nodemailer.createTestAccount()
// create reusable transporter object using the default SMTP transport
const transporter = nodemailer.createTransport({
host: 'smtp.ethereal.email',
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: testAccount.user, // generated ethereal user
pass: testAccount.pass, // generated ethereal password
},
})
transporter.use('compile', hbs({
viewEngine: {
extname: '.hbs', // handlebars extension
partialsDir: 'src/email-templates',
layoutsDir: 'src/email-templates/layouts',
defaultLayout: 'blank',
},
viewPath: 'src/email-templates',
extName: '.hbs'
}))
// send mail with defined transport object
const mailOptions = {
from: 'test#gmail.com', // sender address
to: 'test#gmail.com', // list of receivers
subject: 'Hello ✔', // Subject line
text: 'Hello world?', // plain text body
template: 'hello',
context: {
firstName: 'Clem'
}
}
const info = await transporter.sendMail(mailOptions)
console.log('Message sent: %s', info.messageId)
// Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321#example.com>
// Preview only available when sending through an Ethereal account
console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info))
// Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
} catch (error) {
console.log(error)
}
}

how to send email through amazon ses

I'm using nodemailer and nodemailer-ses-transport.
everytime I run my test code for send mail, I get an error message like this.
but I specified 'From' field in test I don't know why it won't recognize the field.
{ [InvalidParameterValue: Missing required header 'From'.]
message: 'Missing required header \'From\'.',
code: 'InvalidParameterValue',
time: Fri Apr 10 2015 01:34:36 GMT+0000 (UTC),
statusCode: 400,
retryable: false,
retryDelay: 30 }
the test code is here.
please let me know wrong code.
var nodemailer = require('nodemailer');
var ses = require('nodemailer-ses-transport');
var sendAuthCode = function(gmail, message, callback) {
var transporter = nodemailer.createTransport(ses({
accessKeyId : MY_ACCESS_KEY_ID,
secretAccessKey : MY_SECRET_ACEESS_KEY,
region : "us-west-2",
rateLimit : 1
}));
transporter.sendMail({
from: 'mail bot',
to: gmail,
subject: 'TEST',
text: message
}, function(err, resStatus) {
if (err) {
callback(err);
} else {
callback('success');
}
});
}
sendAuthCode("some#gmail.com", "hello", function (result) {
console.log(result);
});
UPDATED
I solved the problem!!
problem was that amazon ses can only send mail between verified email address.
if you want send an email to user who not verified,
you should request to increase ses limit on ses dashboard.
anyway thanks for reply
You cannot use "mail bot" as sender. Use legitimate email.

Getting no records when making Ajax request

I am trying to make a request to a server but im getting no records. When i run the code I am getting no error messages so I assume my code is working but when the callback function is executed on store load I just get a blank message.
var proxy = Ext.data.proxy.Ajax.create({
type:'ajax',
url:loginHostUri,
method:'POST',
headers:{
'Accept':'application/x-www-form-urlencoded'
},
extraParams:{
grant_type:'password',
username:username,
password:psswd,
client_id: consumerKey,
client_secret: consumerSecret
},
reader:{
type:'json',
root:''
}
});
var store = Ext.getStore('instance');
store.setProxy(proxy);
store.load({
callback:function(records,operation,success){
Ext.Msg.alert('INFO',records,Ext.emptyFn);
},
scope:this
});
The message is just blank but I know the Json response looks like this:
{
"":{
"id":"2332123",
"issued_at":"090342",
" instance_url":"instance",
"signature":"sig",
"access_token":"access"
}
}
define a fields or a model for the store
store.setFields({name: 'id', name: 'issued_id' ...});(put this before store.load())
Try that and console.log(records) under callback and reply back what you get...