python - 通过 Gmail 和 Python 发送电子邮件

标签 python oauth-2.0 gmail gmail-api

推荐使用 Gmail 和 Python 发送电子邮件的方式是什么?

有很多 SO 线程,但大多数都是旧的,而且带有用户名和密码的 SMTP 也不再工作,或者用户必须降级其 Gmail 的安全性(例如,参见 here)。

OAuth 是推荐的方式吗?

最佳答案

答案显示了如何使用 gmail API 和 python 发送电子邮件。还更新了发送带有附件的电子邮件的答案。

Gmail API & OAuth -> 无需在脚本中保存用户名和密码。

脚本第一次打开浏览器授权脚本时会在本地存储凭据(它不会存储用户名和密码)。后续运行不需要浏览器,可以直接发送电子邮件。

使用此方法,您不会收到以下 SMTPException 之类的错误,并且无需允许访问不太安全的应用程序:

raise SMTPException("SMTP AUTH extension not supported by server.")  
smtplib.SMTPException: SMTP AUTH extension not supported by server.


以下是使用 gmail API 发送电子邮件的步骤:

Turn on Gmail API steps (向导链接here,更多信息here)

第 2 步:安装 Google 客户端库

pip install --upgrade google-api-python-client

第 3 步: 使用以下脚本发送电子邮件(只需更改主函数中的变量)

import httplib2
import os
import oauth2client
from oauth2client import client, tools, file
import base64
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from apiclient import errors, discovery
import mimetypes
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase

SCOPES = 'https://www.googleapis.com/auth/gmail.send'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Gmail API Python Send Email'

def get_credentials():
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'gmail-python-email-send.json')
    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        credentials = tools.run_flow(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials

def SendMessage(sender, to, subject, msgHtml, msgPlain, attachmentFile=None):
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('gmail', 'v1', http=http)
    if attachmentFile:
        message1 = createMessageWithAttachment(sender, to, subject, msgHtml, msgPlain, attachmentFile)
    else: 
        message1 = CreateMessageHtml(sender, to, subject, msgHtml, msgPlain)
    result = SendMessageInternal(service, "me", message1)
    return result

def SendMessageInternal(service, user_id, message):
    try:
        message = (service.users().messages().send(userId=user_id, body=message).execute())
        print('Message Id: %s' % message['id'])
        return message
    except errors.HttpError as error:
        print('An error occurred: %s' % error)
        return "Error"
    return "OK"

def CreateMessageHtml(sender, to, subject, msgHtml, msgPlain):
    msg = MIMEMultipart('alternative')
    msg['Subject'] = subject
    msg['From'] = sender
    msg['To'] = to
    msg.attach(MIMEText(msgPlain, 'plain'))
    msg.attach(MIMEText(msgHtml, 'html'))
    return {'raw': base64.urlsafe_b64encode(msg.as_bytes())}

def createMessageWithAttachment(
    sender, to, subject, msgHtml, msgPlain, attachmentFile):
    """Create a message for an email.

    Args:
      sender: Email address of the sender.
      to: Email address of the receiver.
      subject: The subject of the email message.
      msgHtml: Html message to be sent
      msgPlain: Alternative plain text message for older email clients          
      attachmentFile: The path to the file to be attached.

    Returns:
      An object containing a base64url encoded email object.
    """
    message = MIMEMultipart('mixed')
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject

    messageA = MIMEMultipart('alternative')
    messageR = MIMEMultipart('related')

    messageR.attach(MIMEText(msgHtml, 'html'))
    messageA.attach(MIMEText(msgPlain, 'plain'))
    messageA.attach(messageR)

    message.attach(messageA)

    print("create_message_with_attachment: file: %s" % attachmentFile)
    content_type, encoding = mimetypes.guess_type(attachmentFile)

    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':
        fp = open(attachmentFile, 'rb')
        msg = MIMEText(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'image':
        fp = open(attachmentFile, 'rb')
        msg = MIMEImage(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'audio':
        fp = open(attachmentFile, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=sub_type)
        fp.close()
    else:
        fp = open(attachmentFile, 'rb')
        msg = MIMEBase(main_type, sub_type)
        msg.set_payload(fp.read())
        fp.close()
    filename = os.path.basename(attachmentFile)
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    message.attach(msg)

    return {'raw': base64.urlsafe_b64encode(message.as_string())}


def main():
    to = "to@address.com"
    sender = "from@address.com"
    subject = "subject"
    msgHtml = "Hi<br/>Html Email"
    msgPlain = "Hi\nPlain Email"
    SendMessage(sender, to, subject, msgHtml, msgPlain)
    # Send message with attachment: 
    SendMessage(sender, to, subject, msgHtml, msgPlain, '/path/to/file.pdf')

if __name__ == '__main__':
    main()

在没有浏览器的情况下在 linux 上运行此代码的提示:
如果您的 linux 环境没有浏览器来完成首次授权过程,您可以在笔记本电脑(mac 或 windows)上运行一次代码,然后将凭据复制到目标 linux 机器。凭证通常存储在以下目的地:

~/.credentials/gmail-python-email-send.json

关于python - 通过 Gmail 和 Python 发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37201250/

相关文章:

python - 如何在 win32com 中迭代工作表?

authentication - OAuth 2.0授权码Grant中 "code"的生命周期

ruby-on-rails - Rails 和 Gmail SMTP,如何使用自定义发件人地址

python,十六进制值转换为字符串/整数

python - 远程服务器设置: nuclide-start-server command doesn't work

python - AttributeError: 'Tensor' 对象没有属性 'numpy'

php - 从 Google OAuth 2.0 PHP API 获取用户信息

php - 使用基于浏览器的 YouTube API 客户端身份验证时,oauth2 的重定向 URI 片段中有额外的字段

php - postfix 在 Ubuntu 15.04 中不发送邮件

python - 如何使用 gmali-api 获取已读和未读或发送和接收的邮件数量?