通过Gmail和Python发送电子邮件

bmvo0sr5  于 2022-09-21  发布在  Python
关注(0)|答案(9)|浏览(388)

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

有很多so线程,但大多数都是旧的,而且使用用户名和密码的SMTP不再起作用,或者用户不得不降低他们Gmail的安全性(例如,参见here)。

OAuth是推荐的方式吗?

sqserrrh

sqserrrh1#

答案展示了如何使用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发送邮件的步骤如下:

(向导链接here,更多信息here)

**第二步:**安装Google客户端库

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

**第三步:**使用以下脚本发送邮件(只需更改Main函数中的变量)

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 = "HinPlain 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
mqkwyuun

mqkwyuun2#

Python Gmail API 'not JSON serializable'的启发,我对其进行了如下修改以使用Python3

import httplib2
import os
import oauth2client
from oauth2client import client, tools
import base64
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from apiclient import errors, discovery

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):
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('gmail', 'v1', http=http)
    message1 = CreateMessage(sender, to, subject, msgHtml, msgPlain)
    SendMessageInternal(service, "me", message1)

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)

def CreateMessage(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'))
    raw = base64.urlsafe_b64encode(msg.as_bytes())
    raw = raw.decode()
    body = {'raw': raw}
    return body

def main():
    to = "to@address.com"
    sender = "from@address.com"
    subject = "subject"
    msgHtml = "Hi<br/>Html Email"
    msgPlain = "HinPlain Email"
    SendMessage(sender, to, subject, msgHtml, msgPlain)

if __name__ == '__main__':
    main()
eivgtgni

eivgtgni3#

以下是发送不带附件(或带附件)的电子邮件所需的Python3.6代码(和解释)。

(要随附件发送,只需取消注解## without attachment下面的2行,并注解## with attachment下面的2行)

阿帕达纳的所有荣誉(和赞成票)

import httplib2
import os
import oauth2client
from oauth2client import client, tools
import base64
from email import encoders

# needed for attachment

import smtplib  
import mimetypes
from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication

# List of all mimetype per extension: http://help.dottoro.com/lapuadlp.php  or http://mime.ritey.com/

from apiclient import errors, discovery  #needed for gmail service

## About credentials

# There are 2 types of "credentials":

# the one created and downloaded from https://console.developers.google.com/apis/ (let's call it the client_id)

# the one that will be created from the downloaded client_id (let's call it credentials, it will be store in C:Usersuser.credentials)

        #Getting the CLIENT_ID 
            # 1) enable the api you need on https://console.developers.google.com/apis/
            # 2) download the .json file (this is the CLIENT_ID)
            # 3) save the CLIENT_ID in same folder as your script.py 
            # 4) update the CLIENT_SECRET_FILE (in the code below) with the CLIENT_ID filename

        #Optional
        # If you don't change the permission ("scope"): 
            #the CLIENT_ID could be deleted after creating the credential (after the first run)

        # If you need to change the scope:
            # you will need the CLIENT_ID each time to create a new credential that contains the new scope.
            # Set a new credentials_path for the new credential (because it's another file)
def get_credentials():
    # If needed create folder for credential
    home_dir = os.path.expanduser('~') #>> C:UsersMe
    credential_dir = os.path.join(home_dir, '.credentials') # >>C:UsersMe.credentials   (it's a folder)
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)  #create folder if doesnt exist
    credential_path = os.path.join(credential_dir, 'cred send mail.json')

    #Store the credential
    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()

    if not credentials or credentials.invalid:
        CLIENT_SECRET_FILE = 'client_id to send Gmail.json'
        APPLICATION_NAME = 'Gmail API Python Send Email'
        #The scope URL for read/write access to a user's calendar data  

        SCOPES = 'https://www.googleapis.com/auth/gmail.send'

        # Create a flow object. (it assists with OAuth 2.0 steps to get user authorization + credentials)
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME

        credentials = tools.run_flow(flow, store)

    return credentials

## Get creds, prepare message and send it

def create_message_and_send(sender, to, subject,  message_text_plain, message_text_html, attached_file):
    credentials = get_credentials()

    # Create an httplib2.Http object to handle our HTTP requests, and authorize it using credentials.authorize()
    http = httplib2.Http()

    # http is the authorized httplib2.Http() 
    http = credentials.authorize(http)        #or: http = credentials.authorize(httplib2.Http())

    service = discovery.build('gmail', 'v1', http=http)

    ## without attachment
    message_without_attachment = create_message_without_attachment(sender, to, subject, message_text_html, message_text_plain)
    send_Message_without_attachment(service, "me", message_without_attachment, message_text_plain)

    ## with attachment
    # message_with_attachment = create_Message_with_attachment(sender, to, subject, message_text_plain, message_text_html, attached_file)
    # send_Message_with_attachment(service, "me", message_with_attachment, message_text_plain,attached_file)

def create_message_without_attachment (sender, to, subject, message_text_html, message_text_plain):
    #Create message container
    message = MIMEMultipart('alternative') # needed for both plain & HTML (the MIME type is multipart/alternative)
    message['Subject'] = subject
    message['From'] = sender
    message['To'] = to

    #Create the body of the message (a plain-text and an HTML version)
    message.attach(MIMEText(message_text_plain, 'plain'))
    message.attach(MIMEText(message_text_html, 'html'))

    raw_message_no_attachment = base64.urlsafe_b64encode(message.as_bytes())
    raw_message_no_attachment = raw_message_no_attachment.decode()
    body  = {'raw': raw_message_no_attachment}
    return body

def create_Message_with_attachment(sender, to, subject, message_text_plain, message_text_html, attached_file):
    """Create a message for an email.

    message_text: The text of the email message.
    attached_file: The path to the file to be attached.

    Returns:
    An object containing a base64url encoded email object.
    """

    ##An email is composed of 3 part :
        #part 1: create the message container using a dictionary { to, from, subject }
        #part 2: attach the message_text with .attach() (could be plain and/or html)
        #part 3(optional): an attachment added with .attach() 

    ## Part 1
    message = MIMEMultipart() #when alternative: no attach, but only plain_text
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject

    ## Part 2   (the message_text)
    # The order count: the first (html) will be use for email, the second will be attached (unless you comment it)
    message.attach(MIMEText(message_text_html, 'html'))
    message.attach(MIMEText(message_text_plain, 'plain'))

    ## Part 3 (attachment) 
    # # to attach a text file you containing "test" you would do:
    # # message.attach(MIMEText("test", 'plain'))

    #-----About MimeTypes:
    # It tells gmail which application it should use to read the attachment (it acts like an extension for windows).
    # If you dont provide it, you just wont be able to read the attachment (eg. a text) within gmail. You'll have to download it to read it (windows will know how to read it with it's extension). 

    #-----3.1 get MimeType of attachment
        #option 1: if you want to attach the same file just specify it’s mime types

        #option 2: if you want to attach any file use mimetypes.guess_type(attached_file) 

    my_mimetype, encoding = mimetypes.guess_type(attached_file)

    # If the extension is not recognized it will return: (None, None)
    # If it's an .mp3, it will return: (audio/mp3, None) (None is for the encoding)
    #for unrecognized extension it set my_mimetypes to  'application/octet-stream' (so it won't return None again). 
    if my_mimetype is None or encoding is not None:
        my_mimetype = 'application/octet-stream' 

    main_type, sub_type = my_mimetype.split('/', 1)# split only at the first '/'
    # if my_mimetype is audio/mp3: main_type=audio sub_type=mp3

    #-----3.2  creating the attachment
        #you don't really "attach" the file but you attach a variable that contains the "binary content" of the file you want to attach

        #option 1: use MIMEBase for all my_mimetype (cf below)  - this is the easiest one to understand
        #option 2: use the specific MIME (ex for .mp3 = MIMEAudio)   - it's a shorcut version of MIMEBase

    #this part is used to tell how the file should be read and stored (r, or rb, etc.)
    if main_type == 'text':
        print("text")
        temp = open(attached_file, 'r')  # 'rb' will send this error: 'bytes' object has no attribute 'encode'
        attachment = MIMEText(temp.read(), _subtype=sub_type)
        temp.close()

    elif main_type == 'image':
        print("image")
        temp = open(attached_file, 'rb')
        attachment = MIMEImage(temp.read(), _subtype=sub_type)
        temp.close()

    elif main_type == 'audio':
        print("audio")
        temp = open(attached_file, 'rb')
        attachment = MIMEAudio(temp.read(), _subtype=sub_type)
        temp.close()            

    elif main_type == 'application' and sub_type == 'pdf':   
        temp = open(attached_file, 'rb')
        attachment = MIMEApplication(temp.read(), _subtype=sub_type)
        temp.close()

    else:                              
        attachment = MIMEBase(main_type, sub_type)
        temp = open(attached_file, 'rb')
        attachment.set_payload(temp.read())
        temp.close()

    #-----3.3 encode the attachment, add a header and attach it to the message
    # encoders.encode_base64(attachment)  #not needed (cf. randomfigure comment)
    #https://docs.python.org/3/library/email-examples.html

    filename = os.path.basename(attached_file)
    attachment.add_header('Content-Disposition', 'attachment', filename=filename) # name preview in email
    message.attach(attachment) 

    ## Part 4 encode the message (the message should be in bytes)
    message_as_bytes = message.as_bytes() # the message should converted from string to bytes.
    message_as_base64 = base64.urlsafe_b64encode(message_as_bytes) #encode in base64 (printable letters coding)
    raw = message_as_base64.decode()  # need to JSON serializable (no idea what does it means)
    return {'raw': raw} 

def send_Message_without_attachment(service, user_id, body, message_text_plain):
    try:
        message_sent = (service.users().messages().send(userId=user_id, body=body).execute())
        message_id = message_sent['id']
        # print(attached_file)
        print (f'Message sent (without attachment) nn Message Id: {message_id}nn Message:nn {message_text_plain}')
        # return body
    except errors.HttpError as error:
        print (f'An error occurred: {error}')

def send_Message_with_attachment(service, user_id, message_with_attachment, message_text_plain, attached_file):
    """Send an email message.

    Args:
    service: Authorized Gmail API service instance.
    user_id: User's email address. The special value "me" can be used to indicate the authenticated user.
    message: Message to be sent.

    Returns:
    Sent Message.
    """
    try:
        message_sent = (service.users().messages().send(userId=user_id, body=message_with_attachment).execute())
        message_id = message_sent['id']
        # print(attached_file)

        # return message_sent
    except errors.HttpError as error:
        print (f'An error occurred: {error}')

def main():
    to = "youremail@gmail.com"
    sender = "myemail@gmail.com"
    subject = "subject test1"
    message_text_html  = r'Hi<br/>Html <b>hello</b>'
    message_text_plain = "HinPlain Email"
    attached_file = r'C:UsersMeDesktopaudio.m4a'
    create_message_and_send(sender, to, subject, message_text_plain, message_text_html, attached_file)

if __name__ == '__main__':
        main()
kxxlusnw

kxxlusnw4#

对于jupyter笔记本用户,在遵循@Apadana的说明后,如果您收到隐晦的错误消息,请确保将代码复制到它自己的python文件中,并使用

%run [filename].py

(仍然不知道我是如何弄明白这一点的)

当你完成这项工作时,你现在就差不多是清白的了。

进行最后一次更改:Gmail API Error from Code Sample - a bytes-like object is required, not 'str'

更换

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

有:

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

现在,它应该™工作了。

结束语:记住,有两个Base64编码的示例...

使用

return {'raw': base64.urlsafe_b64encode(msg.as_string().encode()).decode()}

在方法CreateMessageHtml中

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

在方法createMessageWithAttach中

之所以要这样做,是因为该消息在CreateMessageHtml中的变量名为‘msg’,而在createMessageWithAttach中的变量名为‘Message’。因为原因。怪不得。

9fkzdhlc

9fkzdhlc5#

所以我发现上面所有的方法都非常有帮助,但没有一种方法对我来说是开箱即用的。具体地说,我的问题是找到用来“发送”已读邮件的适当作用域(谷歌提供的快速入门指南中没有指定)。可以在here中找到作用域权限列表。

将其与quickstart guide指南结合使用,我们可以获得如下所示的腌制凭据文件:

import pickle
import os
from google_auth_oauthlib.flow import InstalledAppFlow

# Specify permissions to send and read/write messages

# Find more information at:

# https://developers.google.com/gmail/api/auth/scopes

SCOPES = ['https://www.googleapis.com/auth/gmail.send',
          'https://www.googleapis.com/auth/gmail.modify']

# Get the user's home directory

home_dir = os.path.expanduser('~')

# Recall that the credentials.json data is saved in our "Downloads" folder

json_path = os.path.join(home_dir, 'Downloads', 'credentials.json')

# Next we indicate to the API how we will be generating our credentials

flow = InstalledAppFlow.from_client_secrets_file(json_path, SCOPES)

# This step will generate the pickle file

# The file gmail.pickle stores the user's access and refresh tokens, and is

# created automatically when the authorization flow completes for the first

# time.

creds = flow.run_local_server(port=0)

# We are going to store the credentials in the user's home directory

pickle_path = os.path.join(home_dir, 'gmail.pickle')
with open(pickle_path, 'wb') as token:
    pickle.dump(creds, token)

然后,我们可以使用以下内容实际发送电子邮件:

import pickle
import os
import base64
import googleapiclient.discovery
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# Get the path to the pickle file

home_dir = os.path.expanduser('~')
pickle_path = os.path.join(home_dir, 'gmail.pickle')

# Load our pickled credentials

creds = pickle.load(open(pickle_path, 'rb'))

# Build the service

service = googleapiclient.discovery.build('gmail', 'v1', credentials=creds)

# Create a message

my_email = '<your_email_here>@gmail.com'
msg = MIMEMultipart('alternative')
msg['Subject'] = 'Hello World'
msg['From'] = f'{my_email}'
msg['To'] = f'{my_email}'
msgPlain = 'This is my first email!'
msgHtml = '<b>This is my first email!</b>'
msg.attach(MIMEText(msgPlain, 'plain'))
msg.attach(MIMEText(msgHtml, 'html'))
raw = base64.urlsafe_b64encode(msg.as_bytes())
raw = raw.decode()
body = {'raw': raw}

message1 = body
message = (
    service.users().messages().send(
        userId="me", body=message1).execute())
print('Message Id: %s' % message['id'])

来源:https://scriptreference.com/sending-emails-via-gmail-with-python/

xsuvu9jc

xsuvu9jc6#

更新:我最终没有使用下面我建议的解决方案。在我的例子中,我不得不每周手动获取一次刷新令牌,因为我的OAuth应用程序在Google眼里只是一个测试应用程序或类似的东西……

你应该做的,我最后也做了@miksus下面推荐的:设置一个应用程序密码,并使用你之前在SMTP中用于旧用户名/密码身份验证的相同代码。请注意,这实际上是Google和OAuth一样接受的解决方案,只是(至少在我的情况下)这一点从他们的沟通中非常不清楚。

所以回答你的第二个问题:应用程序密码是(最简单的)推荐方式:安全,代码和以前一样(很少)。我想,额外的安全性来自于这样一个事实,即如果有人破解了你的应用程序密码,你可以简单地撤销它并创建另一个密码。

祝好运!

如果您想使用库,则只需使用以下代码:

from yagmail import SMTP
conn = SMTP("my.email@gmail.com", oauth2_file="./credentials.json")
conn.send(subject="It works!")

第一次运行上面的代码时,您必须提供通过执行下面的步骤1-4获得的客户端ID和客户端密码(如果您还没有的话)。

  • 注意*:第一次运行必须在您可以打开浏览器完成OAuth授权流的计算机上完成(因此很可能不在您的服务器上!)。

代码怎么这么少?

这是一种不需要将大量代码复制粘贴到项目中的解决方案,而是委托给名为yagmail(2.3K⭐ on GitHub)的第三方库,该库:

1.实现了api通信。
1.启动OAuth授权流,如下面的步骤5所示

据我所知,下面描述的所有步骤都是必需的,因此没有更简单的解决方案。此处描述的流程已于2022年5月进行了测试。

1.在Google控制台创建新项目

https://console.cloud.google.com/的Google云控制台中

2.开启Gmail接口

3.配置OAuth同意屏幕

  • 注意:您可能无法选择内部(我没有)。据我所知,这意味着您稍后将有一个额外的步骤,在该步骤中,您将添加要用于发送的电子邮件到“测试者”列表

3.b.启用“Send Mail”OAuth作用域

选择“添加或删除作用域”,然后启用OAuth作用域“发送邮件”。

3.c.添加您的测试用户

  • 这是您要用来发送邮件的邮件
  • 如果在步骤3中选择“外部”,则需要此选项;如果选择“内部”,则可能不需要

4.新建OAuth客户端

OAuth客户端是您的应用程序/脚本,它将使用Gmail API代表您发送邮件。选择一个类型的“桌面应用”。

保存Client IDClient secret--它们向Google唯一标识您的客户端应用程序。在下一步中,您将需要它们。您不必这样做,但您也可以下载包含它们的.json文件。

5.授权客户端APP代发邮件

以下代码告诉yagmail您希望在使用OAuth进行身份验证时发送一封电子邮件:

import yagmail
yag = yagmail.SMTP("my.email@gmail.com", oauth2_file="./credentials.json")
yag.send(subject="It works!")

第一次运行此代码时,它将找不到credentials.json,因此它将:

1.在步骤4中要求您提供您的客户ID和客户密码
1.为您提供一个在浏览器中打开的链接,以遵循OAuth授权流程。在授权流结束时,您将获得一个验证码,并将其粘贴回命令行

完成上述操作后,将创建credentials.json文件并将其保存在启动该进程的文件夹中。该文件包含授权代表您发送电子邮件所需的OAuth令牌。

下次运行代码时,会根据credentials.json中的信息立即发送一封电子邮件。

注:

  • 最后一步必须在您可以打开浏览器完成OAuth授权流的计算机上完成(因此很可能不在您的服务器上!)
  • 拥有credentials.json后,即可将文件复制到您的服务器上
tuwxkamq

tuwxkamq7#

以下是你需要的简单明了的东西:

  • 在您的Google帐户中设置应用程序密码
  • 在您的代码中使用此应用程序密码

设置应用密码

应用

然后,您可以使用smtplib和电子邮件库发送电子邮件:

import smtplib
from email.message import EmailMessage

# Create an email

msg = EmailMessage()
msg['Subject'] = 'An Example Subject'
msg['From'] = "example@gmail.com"
msg['To'] = "receiver@example.com"
msg.set_content("Hi, this is an email.")

# Send the message

s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
s.login("example@gmail.com", "<APP PASSWORD>")
s.send_message(msg)
s.quit()

相应地填写<APP PASSWORD>example@gmail.com

替代方案:红信

我还制作了一个库来简化这一过程(最小化样板并具有几个高级功能)。安装它:

pip install redmail

然后简单地说:

from redmail import gmail

gmail.username = "example@gmail.com"
gmail.password = "<APP PASSWORD>"

gmail.send(
    subject='An Example Subject',
    receivers=['receiver@example.com'],
    text='Hi, this is an example email.'
)

Red Mail支持文本、HTML、内联/嵌入图像、附件,并且它具有集成的JJJA和日志处理程序。

kwvwclae

kwvwclae8#

谢谢,@Guillame,@Apadana。@Guillaume的答案在Win/Python3.7中对我很有效,但有一个变化。对于所有3个print语句,我必须去掉“f”,如下所示:

print (f'An error occurred: {error}')

print ('An error occurred: {error}')

另外,请查看@apandana答案的第一部分,以获取您的Client_sec.json文件。这对我来说更清楚了。

klh5stk1

klh5stk19#

不久前,我被同样的问题缠住了。

在您阅读代码之前-请访问to-https://developers.google.com/gmail/api/quickstart/python

此外,当访问上面列出的站点时,请启用Gmail API,以便可以使用代码。

我不得不在谷歌上搜索了很多次,并修改了已经存在的谷歌Gmail API代码,以找到如下所示:

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from email.mime.text import MIMEText
import base64

subject = "Subject_Goes_Here"
msg = "Your_Message_Text_Goes_Here"
sender = "senders_email@email.com"
receiver = "recievers_email@email.com"

SCOPES = ['https://www.googleapis.com/auth/gmail.modify']
creds = None
if os.path.exists('token.pickle'):
    with open('token.pickle', 'rb') as token:
        creds = pickle.load(token)

# If there are no (valid) credentials available, let the user log in.

if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file(
            'credentials.json', SCOPES)
        creds = flow.run_local_server(port=0)
    # Save the credentials for the next run
    with open('token.pickle', 'wb') as token:
        pickle.dump(creds, token)
service = build('gmail', 'v1', credentials=creds)
message = MIMEText(msg)
message['to'] = receiver
message['from'] = sender
message['subject'] = subject
raw = base64.urlsafe_b64encode(message.as_bytes())
raw = raw.decode()
body = {'raw' : raw}
message = (service.users().messages().send(userId='me', body=body).execute())

这段代码可能看起来很长,但您只需更改变量-subjectmessagesenderreceiver中的值。

我已经根据我的需要修改了代码,它可能不适用于您的代码。然而,网上还有很多其他的例子。例如,要制作带有附件的邮件,您可以转到此处-https://developers.google.com/gmail/api/guides/uploads

在这个例子中,你必须降低你的安全级别,让不太安全的应用程序访问你的Gmail账户。但由于这是一个Google API,您不必担心。这段代码还会询问你的Gmail密码,但这只是作为一种安全措施,由谷歌服务器在本地控制和存储。

这段代码对我很有吸引力,我真的希望它对您也是如此。

谢谢,

相关问题