Python gửi triển vọng email
Email được gửi dưới dạng chuỗi mã hóa base64url trong thuộc tính
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ắnAPI 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 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ănMẫ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 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 https://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'] = '[email protected]' message['From'] = '[email protected]' 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èmTạ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 GitHub ________số 8_______ con trănTươ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 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 https://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'] = '[email protected]' mime_message['From'] = '[email protected]' 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ắnKhi 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 |