Python gửi Gmail có chữ ký

Email được gửi dưới dạng chuỗi mã hóa base64url trong thuộc tính

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;
  }
}
1 của tài nguyên thư. Quy trình công việc cấp cao để gửi email là

  1. 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
  2. Tạo một tài nguyên thư mới và đặt thuộc tính
    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;
      }
    }
    1 của nó thành chuỗi base64url bạn vừa tạo
  3. Gọi cho
    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, hoặc, nếu gửi thư nháp, hãy gọi cho
    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 để 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

Java

Việc tạo một email có thể được đơn giản hóa rất nhiều với lớp

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
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;
  }
}
1

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 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;
  }
}
1 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 trích/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

Java

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ă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

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;
  }
}
1 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

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;
  }
}
0

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 lệnh gọi tớ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;
  }
}
3, như minh họa trong các ví dụ sau

Chủ Đề