Creating draft via Google Gmail API
I had the same issue when I was trying to do this for the first time as well. The solution that I found was to not include the message information as part of the parameters, but rather pass that on in the :body_object as shown below.
@result = client.execute(
:api_method => gmail.users.drafts.create,
:parameters => {
'userId' => "me"
},
:body_object => {
'message' => {
'raw' => Base64.urlsafe_encode64('Test Email Message')
}
}
)
Create email with Gmail API
How to send an email based on a draft with the Gmail API
This is one approach you could take:
Using users.draft list
{
"drafts": [
{
"id": "r-1561xxx",
"message": {
"id": "179891xxx",
"threadId": "179891xxx"
}
}
],
"resultSizeEstimate": 1
}
Then users.draft get
with one of the id
in the previous request:
You can retrieve the current MIME message contained in the draft by calling drafts.get with the parameter format=raw.
(The data is sanitized)
{
"id": "r-1561xxx",
"message": {
"id": "179891xxx",
"threadId": "179891xxx",
"labelIds": [
"DRAFT"
],
"snippet": "Name: Reason: Company:",
"sizeEstimate": 635,
"raw": "TUlNRS1WZXJzaW9uOiAxLjAKRGF0ZTogRnJpLCAxMyBBdWcgMjAyMSAxNjoxMjowOSArMDIwMApNZXNzYWdlLUlEOiA8Q0FGZHVrYm5yZHhReHh4eEBtYWlsLmdtYWlsLmNvbT4KU3ViamVjdDogZHJhZnQxCkZyb206IFNlbmRlciA8c2FtcGxlQGdtYWlsLmNvbT4KVG86IFJlY2VpdmVyIDxzYW1wbGVAZ21haWwuY29tPgpDb250ZW50LVR5cGU6IG11bHRpcGFydC9hbHRlcm5hdGl2ZTsgYm91bmRhcnk9IjAwMDAwMDAwMDAwMGViNGI1ODA1Yzk3MTZmZDIiCgotLTAwMDAwMDAwMDAwMGViNGI1ODA1Yzk3MTZmZDIKQ29udGVudC1UeXBlOiB0ZXh0L3BsYWluOyBjaGFyc2V0PSJVVEYtOCIKCk5hbWU6CgpSZWFzb246CgpDb21wYW55OgoKLS0wMDAwMDAwMDAwMDBlYjRiNTgwNWM5NzE2ZmQyCkNvbnRlbnQtVHlwZTogdGV4dC9odG1sOyBjaGFyc2V0PSJVVEYtOCIKCjxkaXYgZGlyPSJsdHIiPk5hbWU6PGRpdj48YnI+PC9kaXY+PGRpdj5SZWFzb246PC9kaXY+PGRpdj48YnI+PC9kaXY+PGRpdj5Db21wYW55OjwvZGl2PjwvZGl2PgoKLS0wMDAwMDAwMDAwMDBlYjRiNTgwNWM5NzE2ZmQyLS0=",
"historyId": "67xxx",
"internalDate": "1628xxx"
}
}
The raw
attribute is where the message is. It's encoded in base64. Decoded it looks like this:
MIME-Version: 1.0
Date: Fri, 13 Aug 2021 16:12:09 +0200
Message-ID: <CAFdukbnrdxQxxxx@mail.gmail.com>
Subject: draft1
From: Sender <sample@gmail.com>
To: Receiver <sample@gmail.com>
Content-Type: multipart/alternative; boundary="000000000000eb4b5805c9716fd2"
--000000000000eb4b5805c9716fd2
Content-Type: text/plain; charset="UTF-8"
Name:
Reason:
Company:
--000000000000eb4b5805c9716fd2
Content-Type: text/html; charset="UTF-8"
<div dir="ltr">Name:<div><br></div><div>Reason:</div><div><br></div><div>Company:</div></div>
--000000000000eb4b5805c9716fd2--
Sending
In the guide it says:
Create the email content in some convenient way and encode it as a base64url string.
Create a new message resource and set its raw property to the base64url string you just created.
The text should conform to the rfc2822.
So make a plain text email like this (some field you can omit, like date and message ID):
MIME-Version: 1.0
Subject: draft1
From: Sender <sample@gmail.com>
To: Receiver <sample@gmail.com>
Content-Type: multipart/alternative; boundary="000000000000eb4b5805c9716fd2"
--000000000000eb4b5805c9716fd2
Content-Type: text/plain; charset="UTF-8"
Name: TooNetCreation
Reason: TooNetCreation
Company: TooNetCreation
--000000000000eb4b5805c9716fd2
Content-Type: text/html; charset="UTF-8"
<div dir="ltr">Name: TooNetCreation<div><br></div><div>Reason: TooNetCreation</div><div><br></div><div>Company: TooNetCreation</div></div>
--000000000000eb4b5805c9716fd2--
Which encodes to:
TUlNRS1WZXJzaW9uOiAxLjAKU3ViamVjdDogZHJhZnQxCkZyb206IFNlbmRlciA8c2FtcGxlQGdtYWlsLmNvbT4KVG86IFJlY2VpdmVyIDxzYW1wbGVAZ21haWwuY29tPgpDb250ZW50LVR5cGU6IG11bHRpcGFydC9hbHRlcm5hdGl2ZTsgYm91bmRhcnk9IjAwMDAwMDAwMDAwMGViNGI1ODA1Yzk3MTZmZDIiCgotLTAwMDAwMDAwMDAwMGViNGI1ODA1Yzk3MTZmZDIKQ29udGVudC1UeXBlOiB0ZXh0L3BsYWluOyBjaGFyc2V0PSJVVEYtOCIKCk5hbWU6IFRvb05ldENyZWF0aW9uCgpSZWFzb246IFRvb05ldENyZWF0aW9uCgpDb21wYW55OiBUb29OZXRDcmVhdGlvbgoKLS0wMDAwMDAwMDAwMDBlYjRiNTgwNWM5NzE2ZmQyCkNvbnRlbnQtVHlwZTogdGV4dC9odG1sOyBjaGFyc2V0PSJVVEYtOCIKCjxkaXYgZGlyPSJsdHIiPk5hbWU6IFRvb05ldENyZWF0aW9uPGRpdj48YnI+PC9kaXY+PGRpdj5SZWFzb246IFRvb05ldENyZWF0aW9uPC9kaXY+PGRpdj48YnI+PC9kaXY+PGRpdj5Db21wYW55OiBUb29OZXRDcmVhdGlvbjwvZGl2PjwvZGl2PgoKLS0wMDAwMDAwMDAwMDBlYjRiNTgwNWM5NzE2ZmQyLS0=
Which you can send with:
curl --request POST \
'https://gmail.googleapis.com/gmail/v1/users/me/messages/send?key=[YOUR_API_KEY]' \
--header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--data '{"raw":"TUlNRS1WZXJzaW9uOiAxLjAKU3ViamVjdDogZHJhZnQxCkZyb206IFNlbmRlciA8c2FtcGxlQGdtYWlsLmNvbT4KVG86IFJlY2VpdmVyIDxzYW1wbGVAZ21haWwuY29tPgpDb250ZW50LVR5cGU6IG11bHRpcGFydC9hbHRlcm5hdGl2ZTsgYm91bmRhcnk9IjAwMDAwMDAwMDAwMGViNGI1ODA1Yzk3MTZmZDIiCgotLTAwMDAwMDAwMDAwMGViNGI1ODA1Yzk3MTZmZDIKQ29udGVudC1UeXBlOiB0ZXh0L3BsYWluOyBjaGFyc2V0PSJVVEYtOCIKCk5hbWU6IFRvb05ldENyZWF0aW9uCgpSZWFzb246IFRvb05ldENyZWF0aW9uCgpDb21wYW55OiBUb29OZXRDcmVhdGlvbgoKLS0wMDAwMDAwMDAwMDBlYjRiNTgwNWM5NzE2ZmQyCkNvbnRlbnQtVHlwZTogdGV4dC9odG1sOyBjaGFyc2V0PSJVVEYtOCIKCjxkaXYgZGlyPSJsdHIiPk5hbWU6IFRvb05ldENyZWF0aW9uPGRpdj48YnI+PC9kaXY+PGRpdj5SZWFzb246IFRvb05ldENyZWF0aW9uPC9kaXY+PGRpdj48YnI+PC9kaXY+PGRpdj5Db21wYW55OiBUb29OZXRDcmVhdGlvbjwvZGl2PjwvZGl2PgoKLS0wMDAwMDAwMDAwMDBlYjRiNTgwNWM5NzE2ZmQyLS0="}' \
--compressed
After which it should return an instance of the message and you will have send an email!
References
users.draft list
users.draft get
users.messages send
- Sending email guide
Working with drafts guide
How to create draft message with attachment using gmail API in Node.JS?
After some research, I found a solution to attach an image while create a draft using Gmail API, I got the hint from this source Sending mail with attachment
This is the complete working example:
Step 1:
function makeBody(subject, message, receiverId) {
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;
}
Step 2:
const auth = await authorize(accessToken);
const gmail = google.gmail({
version: 'v1',
auth
});
var rawText = makeBody("This is subject", "This is message", "test@gmail.com");
var res = await gmail.users.drafts.create({
'userId': 'me',
'resource': {
'message': {
'raw': rawText
}
}
});
Also can use this npm package mimemessage
How to open a draft created with Gmail API in browser?
The way to make this url changed, now it works like this:
mail.google.com/mail/#inbox?compose=draft.message.id
If you list your drafts you get
{
"drafts": [
{
"id": "r5632827412362757569",
"message": {
"id": "174f4fa0dd96af123",
"threadId": "174f4f59344d6321"
}
}
],
...
}
So, to open this draft you need the following url :
mail.google.com/mail/#inbox?compose=174f4fa0dd96af123
Gmail Api Create Draft Reply
Thank you all for the comments you left. You were all right on different points.
The problem was that I was using a slightly different example to the one on the Docs page.
I found the code here worked: https://developers.google.com/gmail/api/guides/drafts
It can be used like so:
msg = create_message('YOU@gmail.com','THEM@company.com','Re: Some Subject','This is a test')
create_draft(service,'me', msg)
Create a draft with PDF file as attachment using Gmail API in Java
Try something similar to this:
private MimeMessage createEmailWithAttachment(String to,
String subject,
String bodyText,
File file) throws MessagingException, IOException {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
MimeMessage email = new MimeMessage(session);
email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
email.setSubject(subject);
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(bodyText, "text/plain");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);
mimeBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(file);
mimeBodyPart.setDataHandler(new DataHandler(source));
mimeBodyPart.setFileName(file.getName());
multipart.addBodyPart(mimeBodyPart);
email.setContent(multipart);
return email;
}
Related Topics
Why Use "Self" to Access Activerecord/Rails Model Properties
How to Match Accented Characters With a Regex
Using Layouts in Haml Files Independently of Rails
Extract Number from String in Ruby
Rails 4.0 Strong Parameters Nested Attributes With a Key That Points to a Hash
What Does Class_Eval ≪≪-"End_Eval", _File_, _Line_ Mean in Ruby
Why Are Methods in Ruby Documentation Preceded by a Hash Sign
String Interpolation in Ruby Doesn't Work
Best Practices to Handle Routes For Sti Subclasses in Rails
Iterate Through Every File in One Directory
Why Isn't Current Directory on My Ruby Path
Convert Array of 2-Element Arrays into a Hash, Where Duplicate Keys Append Additional Values
How to 'Bundle Install' When Your Gemfile Requires an Older Version of Bundler