使用 Mail API 傳送郵件

本指南說明如何使用 Mail API 傳送郵件。

Mail API 提供兩種傳送電子郵件訊息的方式:mail.send_mail() 函式和 EmailMessage 類別。

傳送作業並非同步:mail.send_mail() 函式和 EmailMessage.send() 方法會先將訊息資料傳輸至郵件服務,然後再傳回。郵件服務將訊息排入佇列後會嘗試傳送訊息,並在目的地郵件伺服器無法使用時重新嘗試。錯誤訊息和退件通知會傳送到寄件者的電子郵件地址。

事前準備

將您的寄件者電子郵件註冊為已獲授權的寄件者。詳情請參閱可以傳送電子郵件的人員一節。

使用「mail.send_mail()」傳送郵件

如要使用 mail.send_mail() 函式傳送郵件,請將電子郵件訊息的欄位當做參數,當中包含寄件者、收件者、訊息主旨和訊息內文。例如:

    mail.send_mail(sender=sender_address,
                   to="Albert Johnson <Albert.Johnson@example.com>",
                   subject="Your account has been approved",
                   body="""Dear Albert:

Your example.com account has been approved.  You can now visit
http://www.example.com/ and sign in using your Google Account to
access new features.

Please let us know if you have any questions.

The example.com Team
""")

使用「EmailMessage」傳送郵件

如要搭配使用物件和 EmailMessage 類別來傳送郵件,請將電子郵件訊息的欄位傳送至 EmailMessage 建構函式,並利用執行個體屬性更新訊息。

EmailMessage.send() 方法可以傳送以執行個體屬性呈現的電子郵件訊息。應用程式可以修改屬性並再次呼叫 send() 方法,重複使用 EmailMessage 執行個體。

    message = mail.EmailMessage(
        sender=sender_address,
        subject="Your account has been approved")

    message.to = "Albert Johnson <Albert.Johnson@example.com>"
    message.body = """Dear Albert:

Your example.com account has been approved.  You can now visit
http://www.example.com/ and sign in using your Google Account to
access new features.

Please let us know if you have any questions.

The example.com Team
"""
    message.send()

傳送大量郵件

如要查看傳送大量電子郵件的注意事項,請參閱大量郵件指南

如要進一步瞭解 Mail API 的遷移注意事項,請參閱「郵件處理常式」指南。