发送邮件

邮件 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()

以下示例演示了如何通过发送邮件来确认电子邮件地址:

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)

群发邮件

如需了解群发电子邮件的注意事项,请参阅群发邮件准则