1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > gmail怎么发送html 如何通过gmail api for python发送HTML格式的电子邮件

gmail怎么发送html 如何通过gmail api for python发送HTML格式的电子邮件

时间:2023-02-21 17:42:21

相关推荐

gmail怎么发送html 如何通过gmail api for python发送HTML格式的电子邮件

使用GMail API Example: Send Mail中的示例代码,在遵循身份验证规则之后,通过gmail帐户发送以编程方式生成的电子邮件就足够简单了。从这个例子中不明显的是如何将电子邮件设置为HTML格式。

问题

如何使用python在gmail api发送消息时获取HTML格式?

我有这个…

message_body = "Hello!\nYou've just received a test message!\n\nSincerely,\n-Test Message Generator\n"

我希望是这样…Hello!

You've just received a test message!

Sincerely,

-Test Message Generator

来自GMail API的示例源代码

下面是示例的稍微修改版本,但仍然有效:import argparse

import base64

from pprint import pformat

from pprint import pprint

import httplib2

import os

from email.MIMEMultipart import MIMEMultipart

from email.MIMEText import MIMEText

from apiclient import discovery

from oauth2client import client

from oauth2client import tools

from oauth2client.file import Storage

SCOPES = '/'

CLIENT_SECRET_FILE = 'client_secret.json'

APPLICATION_NAME = 'Test EMail App'

def get_credentials():

"""Gets valid user credentials from storage.

If nothing has been stored, or if the stored credentials are invalid,

the OAuth2 flow is completed to obtain the new credentials.

Returns:

Credentials, the obtained credential.

"""

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-quickstart.json')

store = 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

if flags:

credentials = tools.run_flow(flow, store, flags)

else: # Needed only for compatibility with Python 2.6

credentials = tools.run(flow, store)

print('Storing credentials to ' + credential_path)

return credentials

def create_message(sender, to, cc, subject, message_text):

"""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.

message_text: The text of the email message.

Returns:

An object containing a base64url encoded email object.

"""

print(sender + ', ' + to + ', ' + subject + ', ' + message_text)

message = MIMEText(message_text)

message['to'] = to

message['from'] = sender

message['subject'] = subject

message['cc'] = cc

pprint(message)

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

def send_message(service, user_id, message_in):

"""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.

"""

pprint(message_in)

try:

message = (service.users().messages().send(userId=user_id, body=message_in).execute())

pprint(message)

print ('Message Id: %s' % message['id'])

return message

except errors.HttpError, error:

print ('An error occurred: %s' % error)

def main(cli):

"""Shows basic usage of the Gmail API.

Creates a Gmail API service object and outputs a list of label names

of the user's Gmail account.

"""

credentials = get_credentials()

http = credentials.authorize(httplib2.Http())

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

email_msg = create_message(cli.addr_from, cli.addr_to, cli.addr_cc, cli.subject, cli.message)

msg_out = service.users().messages().send(userId = 'me', body = email_msg).execute()

pprint(msg_out)

if __name__ == '__main__':

parser = argparse.ArgumentParser()

parser.add_argument('-m', '--message', help = 'The message to send in the email', default='')

parser.add_argument('-t', '--addr_to', help = 'the list of comma separated emails to send', default='cbsd.tools@')

parser.add_argument('-s', '--subject', help = 'the email subject', default='')

parser.add_argument('-c', '--addr_cc', help = 'email CC\'s', default='')

parser.add_argument('-f', '--addr_from', help = 'Email address to send from', default='cbsd.tools@')

cli = parser.parse_args()

pprint(dir(cli))

main(cli)

尽管我已经尽了最大努力,但使用这段代码及其变体,我无法获取html格式的代码,也无法获取简单的转义字符,以便在需要的地方创建回车。

这是不起作用的

尝试以下操作也不起作用:正在修改line 69以添加其他消息字典参数。。。即。

{'raw': base64.urlsafe_b64encode(message.as_string()), 'payload': {'mimeType': 'text/html'}}

在消息文本中添加各种转义反斜杠:

\n。。。也就是说:\\n或者\\\n并且仅仅呈现为那些精确的字符

添加

并没有添加新行,只是呈现为那些确切的字符

添加\r并没有添加新行,只是呈现为确切的字符

为什么这不是一个重复的问题This SO link deals with multipart/signed messages我对多部分消息传递不感兴趣,因为它是一个不雅的解决方案。我希望整个消息都是HTML。

此外,这个链接没有被接受的答案,而且只有一个答案是非答案,因为它只是简单地说明他们正在向谷歌发送一个问题陈述。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。