如何在python中发送gmail电子邮件,同时包括默认的电子邮件签名和字体大小?

问题描述

我正在尝试使用 Python 通过 Gmail 发送电子邮件。但是,我想添加已在 Gmail 设置中指定的电子邮件签名和字体大小(大号)。以下是发送电子邮件代码;我需要添加什么来完成这个要求?

代码如下:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

subject = "Offer"
message = "My offer is 2 dollars"


email = "sender@gmail.com"  
password ='mypassword'
send_to_email = "recipient@gmail.com"  

msg = MIMEMultipart()
msg["From"] = email
msg["To"] = send_to_email
msg["Subject"] = subject

msg.attach(MIMEText(message,'plain'))

server = smtplib.SMTP("smtp.gmail.com",587)
server.starttls()
server.login(email,password)
text = msg.as_string()
server.sendmail(email,send_to_email,text)
server.quit()

解决方法

纯文本 MIME 部分 (width: "100",) 没有字体大小;它们只是没有任何格式化工具的 ASCII 文本(超出 ASCII 提供的内容,即换行符和制表符)。

如果您想嵌入格式,请发送 HTML 电子邮件。

顺便说一句,您的代码看起来像是 Python 3.6 之前的版本; text/plain 库在该版本中进行了重大改革。新代码通常应该针对新的 email API,它比旧的更直接,也更通用,旧的需要您在每条消息中明确设置 MIME 结构。请参阅 the examples in the documentation 以获得良好的起点。