Python 使用gmail api发送电子邮件

Python 使用gmail api发送电子邮件,python,gmail,google-oauth,gmail-api,mime,Python,Gmail,Google Oauth,Gmail Api,Mime,我正在编写一个使用google api发送电子邮件的简单脚本: 我的代码如下所示: 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 err

我正在编写一个使用google api发送电子邮件的简单脚本: 我的代码如下所示:

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
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_string())}



def main():
    to = "user@gmail.com"
    sender = "user@gmail.com"
    subject = "testing"
    msgHtml = "Hi<br/>Html Email"
    msgPlain = "Hi\nPlain Email"
    SendMessage(sender, to, subject, msgHtml, msgPlain)

if __name__ == '__main__':
    main()
导入httplib2
导入操作系统
导入oauth2client
从oauth2client导入客户端,工具
导入base64
从email.mime.multipart导入MIMEMultipart
从email.mime.text导入MIMEText
从apiclient导入错误,发现
导入模拟类型
从email.mime.image导入MIMEImage
从email.mime.audio导入MIMEAudio
从email.mime.base导入MIMEBase
范围https://www.googleapis.com/auth/gmail.send'
CLIENT\u SECRET\u FILE='CLIENT\u SECRET.json'
应用程序名称='Gmail API Python发送电子邮件'
def get_凭据():
home\u dir=os.path.expanduser(“~”)
credential_dir=os.path.join(home_dir,“.credentials”)
如果操作系统路径不存在(凭证目录):
os.makedirs(凭证目录)
credential\u path=os.path.join(credential\u dir,
'gmail python email send.json')
store=oauth2client.file.Storage(凭证路径)
凭据=store.get()
如果不是凭据或凭据。无效:
flow=client.flow\u from\u clientsecrets(client\u SECRET\u文件,作用域)
flow.user\u agent=应用程序\u名称
凭据=工具。运行\u流(流、存储)
打印('将凭证存储到'+凭证路径)
返回凭证
def SendMessage(发件人、收件人、主题、msgHtml、msgPlain、附件文件=无):
凭证=获取凭证()
http=credentials.authorize(httplib2.http())
service=discovery.build('gmail','v1',http=http)
如果是附件文件:
message1=createMessageWithAttachment(发件人、收件人、主题、msgHtml、msgPlain、attachmentFile)
其他:
message1=CreateMessageHtml(发件人、收件人、主题、msgHtml、msgPlain)
结果=SendMessageInternal(服务,“我”,消息1)
返回结果
def SendMessageInternal(服务、用户id、消息):
尝试:
message=(service.users().messages().send(userId=user\u id,body=message).execute())
打印('消息Id:%s'%Message['Id']))
回信
除了errors.HttpError作为错误:
打印('发生错误:%s'%1错误)
返回“错误”
返回“OK”
def CreateMessageHtml(发件人、收件人、主题、msgHtml、msgPlain):
msg=MIMEMultipart('alternative')
msg['Subject']=主语
msg['From']=发件人
msg['To']=To
msg.attach(MIMEText(msgPlain,'plain'))
附加(MIMEText(msgHtml,'html'))
返回{'raw':base64.urlsafe_b64encode(msg.as_string())}
def main():
to=”user@gmail.com"
发送方=”user@gmail.com"
主题=“测试”
msgHtml=“嗨
Html电子邮件” msgPlain=“您好\n打印电子邮件” SendMessage(发件人、收件人、主题、msgHtml、msgPlain) 如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu': main()
但是,当我运行此脚本时,会出现以下错误:

我去确保文件存在,并导航到路径。目录包含以下文件:


显然clientsecrets.py文件确实存在。我不确定如何解决此错误,因为文件明显存在,并且终端确实正确映射了文件。如有任何建议,将不胜感激。谢谢大家!

在您的错误消息中,我们看不到这样的文件或目录:“client_secret.json”。您是否拥有它,然后将其存储在当前目录中?如果没有,您可以查看如何使用


别忘了打开gmail API

在上图的错误消息中,它可以看到
没有这样的文件或目录:“client\u secret.json”
。有吗?如果您没有,您可以在步骤1中查看如何检索
client\u secret.json
:打开的Gmail API。谢谢!我会调查的!!