python - 如何使用 Python 中的 smtplib 发送文本或 word 文件?
问题描述
我在谷歌上搜索过,但这些例子对于像我这样的初学者来说有点难。如果有任何简单的例子......我知道如何发送基于 html 的消息
解决方案
import smtplib
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
def send_mail(send_from,password send_to, subject, text, file=None,
server="127.0.0.1"):
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = COMMASPACE.join(send_to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach(MIMEText(text))
with open(file, "rb") as fil:
part = MIMEApplication(
fil.read(),
Name=basename(file)
)
# After the file is closed
part['Content-Disposition'] = 'attachment; filename="%s"' % basename(file)
msg.attach(part)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(send_from, password )
text = msg.as_string()
server.sendmail(send_from, send_to, text)
server.quit()
send_mail('From','Password','ToMail','Subject','msg',r'FullPath')
推荐阅读
- javascript - 预渲染链接属性不会导致资源加载
- xml - XML - XSL 修改导出到 Excel 以设置文本/单元格数
- python - NIM 游戏,范围在 1 和 1 之间时随机范围有错误,需要快速修复(不重复)
- python - 需要命令返回值的 Tkinter 按钮
- python - 多维python列表元素分配错误
- .htaccess - 拒绝访问 index.php 文件 - Apache
- javascript - 检测 Firefox 中的自动填充输入
- java - 如何解析这个简单的 JSON
- python - 为什么 MATLAB 2D Char Array 会变成 Python 1D 数组?
- asp.net - 如何在 AWS 上部署 IdentityServer4