将电子邮件编码为Python 3中的base64

问题描述 投票:0回答:1

我正在根据说明here编码为base64,使用gmail创建和发送电子邮件。

我以这种方式创建消息:

import smtplib
from email.mime.text import MIMEText
import base64
to='[email protected]'
sender = '[email protected]'
subject = 'Menu'
message_text = 'Spam'
message = MIMEText(message_text)
message['to'] = to
message['from'] = sender
message['subject'] = subject

但是,当我转换为base64时

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

我收到此错误:TypeError: a bytes-like object is required, not 'str'

所以我尝试这个:

msg = {'raw': base64.urlsafe_b64encode(message.as_bytes())}

但是,当我来发送消息时

send_message(service=service,
             user_id = 'me', 
             message = msg)

我收到此错误:Object of type bytes is not JSON serializable

所以,我该如何格式化消息? (我认为这可能与Python 3 / Python 2的差异有关,但不能确定)

python email gmail smtplib base64url
1个回答
0
投票

此代码可用于发送电子邮件。

确保不太安全的应用程序已被您的gmail帐户关闭。

import requests
import smtplib
from email.mime.text import MIMEText

email_id = ""
email_pws = ""

TO = '[email protected]'
SUBJECT = 'Test Mail'
TEXT = 'email text'


def send_email(subject, body, toaddr="[email protected]"):
    fromaddr = email_id
    msg = MIMEText(body, 'plain')
    msg['To'] = toaddr
    msg['Subject'] = subject

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(email_id, email_pws)
    server.sendmail(fromaddr, toaddr, msg.as_string())
    server.quit()

send_email(SUBJECT, TEXT, TO)
© www.soinside.com 2019 - 2024. All rights reserved.