Email được gửi dưới dạng chuỗi mã hóa base64url trong thuộc tính raw
của tài nguyên thư. Quy trình làm việc cấp cao để gửi email là
- Tạo nội dung email theo một số cách thuận tiện và mã hóa nó dưới dạng chuỗi base64url
- Tạo một tài nguyên tin nhắn mới và đặt thuộc tính
raw
của nó thành chuỗi base64url bạn vừa tạo - Gọi cho
messages.send
, hoặc, nếu gửi thư nháp, hãy gọi chodrafts.send
để gửi tin nhắn
Các chi tiết của quy trình làm việc này có thể khác nhau tùy thuộc vào sự lựa chọn của bạn về thư viện máy khách và ngôn ngữ lập trình
Tạo tin nhắn
API Gmail yêu cầu thư email MIME tuân thủ RFC 2822 và được mã hóa dưới dạng chuỗi base64url. Nhiều ngôn ngữ lập trình có thư viện hoặc tiện ích giúp đơn giản hóa quá trình tạo và mã hóa thông báo MIME. Các ví dụ mã sau minh họa cách tạo thông báo MIME bằng thư viện ứng dụng khách Google API cho các ngôn ngữ khác nhau
Việc tạo một email có thể được đơn giản hóa rất nhiều với lớp Java
import com.google.api.services.gmail.model.Message;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.apache.commons.codec.binary.Base64;
/* Class to demonstrate the use of Gmail Create Message API */
public class CreateMessage {
/**
* Create a message from an email.
*
* @param emailContent Email to be set to raw of message
* @return a message containing a base64url encoded email
* @throws IOException - if service account credentials file not found.
* @throws MessagingException - if a wrongly formatted address is encountered.
*/
public static Message createMessageWithEmail[MimeMessage emailContent]
throws MessagingException, IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream[];
emailContent.writeTo[buffer];
byte[] bytes = buffer.toByteArray[];
String encodedEmail = Base64.encodeBase64URLSafeString[bytes];
Message message = new Message[];
message.setRaw[encodedEmail];
return message;
}
}
3 trong gói import com.google.api.services.gmail.model.Message;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.apache.commons.codec.binary.Base64;
/* Class to demonstrate the use of Gmail Create Message API */
public class CreateMessage {
/**
* Create a message from an email.
*
* @param emailContent Email to be set to raw of message
* @return a message containing a base64url encoded email
* @throws IOException - if service account credentials file not found.
* @throws MessagingException - if a wrongly formatted address is encountered.
*/
public static Message createMessageWithEmail[MimeMessage emailContent]
throws MessagingException, IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream[];
emailContent.writeTo[buffer];
byte[] bytes = buffer.toByteArray[];
String encodedEmail = Base64.encodeBase64URLSafeString[bytes];
Message message = new Message[];
message.setRaw[encodedEmail];
return message;
}
}
4. Ví dụ sau đây cho biết cách tạo thư email, bao gồm các tiêu đề
gmail/đoạn mã/src/main/java/TạoEmail. java
Xem trên GitHub
import java.util.Properties; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; /* Class to demonstrate the use of Gmail Create Email API */ public class CreateEmail { /** * Create a MimeMessage using the parameters provided. * * @param toEmailAddress email address of the receiver * @param fromEmailAddress email address of the sender, the mailbox account * @param subject subject of the email * @param bodyText body text of the email * @return the MimeMessage to be used to send email * @throws MessagingException - if a wrongly formatted address is encountered. */ public static MimeMessage createEmail[String toEmailAddress, String fromEmailAddress, String subject, String bodyText] throws MessagingException { Properties props = new Properties[]; Session session = Session.getDefaultInstance[props, null]; MimeMessage email = new MimeMessage[session]; email.setFrom[new InternetAddress[fromEmailAddress]]; email.addRecipient[javax.mail.Message.RecipientType.TO, new InternetAddress[toEmailAddress]]; email.setSubject[subject]; email.setText[bodyText]; return email; } }
Bước tiếp theo là mã hóa
import com.google.api.services.gmail.model.Message; import java.io.ByteArrayOutputStream; import java.io.IOException; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import org.apache.commons.codec.binary.Base64; /* Class to demonstrate the use of Gmail Create Message API */ public class CreateMessage { /** * Create a message from an email. * * @param emailContent Email to be set to raw of message * @return a message containing a base64url encoded email * @throws IOException - if service account credentials file not found. * @throws MessagingException - if a wrongly formatted address is encountered. */ public static Message createMessageWithEmail[MimeMessage emailContent] throws MessagingException, IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream[]; emailContent.writeTo[buffer]; byte[] bytes = buffer.toByteArray[]; String encodedEmail = Base64.encodeBase64URLSafeString[bytes]; Message message = new Message[]; message.setRaw[encodedEmail]; return message; } }3, khởi tạo đối tượng
import com.google.api.services.gmail.model.Message; import java.io.ByteArrayOutputStream; import java.io.IOException; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import org.apache.commons.codec.binary.Base64; /* Class to demonstrate the use of Gmail Create Message API */ public class CreateMessage { /** * Create a message from an email. * * @param emailContent Email to be set to raw of message * @return a message containing a base64url encoded email * @throws IOException - if service account credentials file not found. * @throws MessagingException - if a wrongly formatted address is encountered. */ public static Message createMessageWithEmail[MimeMessage emailContent] throws MessagingException, IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream[]; emailContent.writeTo[buffer]; byte[] bytes = buffer.toByteArray[]; String encodedEmail = Base64.encodeBase64URLSafeString[bytes]; Message message = new Message[]; message.setRaw[encodedEmail]; return message; } }6 và đặt chuỗi thông báo được mã hóa base64url làm giá trị của thuộc tính
raw
gmail/đoạn trích/src/main/java/CreateMessage. java
Xem trên GitHub
import com.google.api.services.gmail.model.Message; import java.io.ByteArrayOutputStream; import java.io.IOException; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import org.apache.commons.codec.binary.Base64; /* Class to demonstrate the use of Gmail Create Message API */ public class CreateMessage { /** * Create a message from an email. * * @param emailContent Email to be set to raw of message * @return a message containing a base64url encoded email * @throws IOException - if service account credentials file not found. * @throws MessagingException - if a wrongly formatted address is encountered. */ public static Message createMessageWithEmail[MimeMessage emailContent] throws MessagingException, IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream[]; emailContent.writeTo[buffer]; byte[] bytes = buffer.toByteArray[]; String encodedEmail = Base64.encodeBase64URLSafeString[bytes]; Message message = new Message[]; message.setRaw[encodedEmail]; return message; } }
con trăn
Mẫu mã sau đây minh họa việc tạo một thông báo MIME, mã hóa thành chuỗi base64url và gán nó cho trường raw
của tài nguyên
import com.google.api.services.gmail.model.Message; import java.io.ByteArrayOutputStream; import java.io.IOException; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import org.apache.commons.codec.binary.Base64; /* Class to demonstrate the use of Gmail Create Message API */ public class CreateMessage { /** * Create a message from an email. * * @param emailContent Email to be set to raw of message * @return a message containing a base64url encoded email * @throws IOException - if service account credentials file not found. * @throws MessagingException - if a wrongly formatted address is encountered. */ public static Message createMessageWithEmail[MimeMessage emailContent] throws MessagingException, IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream[]; emailContent.writeTo[buffer]; byte[] bytes = buffer.toByteArray[]; String encodedEmail = Base64.encodeBase64URLSafeString[bytes]; Message message = new Message[]; message.setRaw[encodedEmail]; return message; } }6
gmail/đoạn mã/gửi thư/create_draft. py
Xem trên GitHub
from __future__ import print_function import base64 from email.message import EmailMessage import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def gmail_create_draft[]: """Create and insert a draft email. Print the returned draft's message and id. Returns: Draft object, including draft id and message meta data. Load pre-authorized user credentials from the environment. TODO[developer] - See //developers.google.com/identity for guides on implementing OAuth2 for the application. """ creds, _ = google.auth.default[] try: # create gmail api client service = build['gmail', 'v1', credentials=creds] message = EmailMessage[] message.set_content['This is automated draft mail'] message['To'] = 'gduser1@workspacesamples.dev' message['From'] = 'gduser2@workspacesamples.dev' message['Subject'] = 'Automated draft' # encoded message encoded_message = base64.urlsafe_b64encode[message.as_bytes[]].decode[] create_message = { 'message': { 'raw': encoded_message } } # pylint: disable=E1101 draft = service.users[].drafts[].create[userId="me", body=create_message].execute[] print[F'Draft id: {draft["id"]}\nDraft message: {draft["message"]}'] except HttpError as error: print[F'An error occurred: {error}'] draft = None return draft if __name__ == '__main__': gmail_create_draft[]
Tạo tin nhắn có tệp đính kèm
Tạo thư có tệp đính kèm giống như tạo bất kỳ thư nào khác, nhưng quá trình tải tệp lên dưới dạng thư MIME nhiều phần phụ thuộc vào ngôn ngữ lập trình. Các ví dụ mã sau minh họa các cách khả thi để tạo thông báo MIME nhiều phần có tệp đính kèm
Ví dụ sau đây cho thấy cách tạo một thông báo MIME nhiều phần, các bước mã hóa và gán tương tự như trên gmail/đoạn trích/src/main/java/Tạo bản thảo với tệp đính kèm. java Xem trên GitHubJava
________số 8_______
con trăn
Tương tự như ví dụ trước, ví dụ này cũng xử lý việc mã hóa thông báo thành base64url và gán nó cho trường raw
của tài nguyên
import com.google.api.services.gmail.model.Message; import java.io.ByteArrayOutputStream; import java.io.IOException; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import org.apache.commons.codec.binary.Base64; /* Class to demonstrate the use of Gmail Create Message API */ public class CreateMessage { /** * Create a message from an email. * * @param emailContent Email to be set to raw of message * @return a message containing a base64url encoded email * @throws IOException - if service account credentials file not found. * @throws MessagingException - if a wrongly formatted address is encountered. */ public static Message createMessageWithEmail[MimeMessage emailContent] throws MessagingException, IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream[]; emailContent.writeTo[buffer]; byte[] bytes = buffer.toByteArray[]; String encodedEmail = Base64.encodeBase64URLSafeString[bytes]; Message message = new Message[]; message.setRaw[encodedEmail]; return message; } }6
gmail/đoạn mã/gửi thư/create_draft_with_attachment. py
Xem trên GitHub
from __future__ import print_function import base64 import mimetypes import os from email.message import EmailMessage from email.mime.audio import MIMEAudio from email.mime.base import MIMEBase from email.mime.image import MIMEImage from email.mime.text import MIMEText import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def gmail_create_draft_with_attachment[]: """Create and insert a draft email with attachment. Print the returned draft's message and id. Returns: Draft object, including draft id and message meta data. Load pre-authorized user credentials from the environment. TODO[developer] - See //developers.google.com/identity for guides on implementing OAuth2 for the application. """ creds, _ = google.auth.default[] try: # create gmail api client service = build['gmail', 'v1', credentials=creds] mime_message = EmailMessage[] # headers mime_message['To'] = 'gduser1@workspacesamples.dev' mime_message['From'] = 'gduser2@workspacesamples.dev' mime_message['Subject'] = 'sample with attachment' # text mime_message.set_content[ 'Hi, this is automated mail with attachment.' 'Please do not reply.' ] # attachment attachment_filename = 'photo.jpg' # guessing the MIME type type_subtype, _ = mimetypes.guess_type[attachment_filename] maintype, subtype = type_subtype.split['/'] with open[attachment_filename, 'rb'] as fp: attachment_data = fp.read[] mime_message.add_attachment[attachment_data, maintype, subtype] encoded_message = base64.urlsafe_b64encode[mime_message.as_bytes[]].decode[] create_draft_request_body = { 'message': { 'raw': encoded_message } } # pylint: disable=E1101 draft = service.users[].drafts[].create[userId="me", body=create_draft_request_body]\ .execute[] print[F'Draft id: {draft["id"]}\nDraft message: {draft["message"]}'] except HttpError as error: print[F'An error occurred: {error}'] draft = None return draft def build_file_part[file]: """Creates a MIME part for a file. Args: file: The path to the file to be attached. Returns: A MIME part that can be attached to a message. """ content_type, encoding = mimetypes.guess_type[file] if content_type is None or encoding is not None: content_type = 'application/octet-stream' main_type, sub_type = content_type.split['/', 1] if main_type == 'text': with open[file, 'rb']: msg = MIMEText['r', _subtype=sub_type] elif main_type == 'image': with open[file, 'rb']: msg = MIMEImage['r', _subtype=sub_type] elif main_type == 'audio': with open[file, 'rb']: msg = MIMEAudio['r', _subtype=sub_type] else: with open[file, 'rb']: msg = MIMEBase[main_type, sub_type] msg.set_payload[file.read[]] filename = os.path.basename[file] msg.add_header['Content-Disposition', 'attachment', filename=filename] return msg if __name__ == '__main__': gmail_create_draft_with_attachment[]
Gửi tin nhắn
Khi bạn đã tạo một tin nhắn, bạn có thể gửi nó bằng cách cung cấp nó trong phần yêu cầu của cuộc gọi tới messages.send
, như minh họa trong các ví dụ sau