傳送郵件

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 <[email protected]>",
                   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 <[email protected]>"
    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()

下列範例示範如何透過傳送訊息來確認電子郵件地址:

class UserSignupHandler(webapp2.RequestHandler):
    """Serves the email address sign up form."""

    def post(self):
        user_address = self.request.get('email_address')

        if not mail.is_email_valid(user_address):
            self.get()  # Show the form again.
        else:
            confirmation_url = create_new_user_confirmation(user_address)
            sender_address = (
                'Example.com Support <{}@appspot.gserviceaccount.com>'.format(
                    app_identity.get_application_id()))
            subject = 'Confirm your registration'
            body = """Thank you for creating an account!
Please confirm your email address by clicking on the link below:

{}
""".format(confirmation_url)
            mail.send_mail(sender_address, user_address, subject, body)

傳送大量郵件

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