python - 如何使用 SMTP 发送附件?

标签 python email smtp attachment smtplib

我想编写一个使用 Python 的 smtplib 发送电子邮件的程序.我搜索了文档和 RFC,但找不到与附件相关的任何内容。因此,我确信我错过了一些更高层次的概念。有人能告诉我附件在 SMTP 中是如何工作的吗?

最佳答案

这是一个带有 PDF 附件、文本“正文”并通过 Gmail 发送的邮件示例。

# Import smtplib for the actual sending function
import smtplib

# For guessing MIME type
import mimetypes

# Import the email modules we'll need
import email
import email.mime.application

# Create a text/plain message
msg = email.mime.Multipart.MIMEMultipart()
msg['Subject'] = 'Greetings'
msg['From'] = 'xyz@gmail.com'
msg['To'] = 'abc@gmail.com'

# The main body is just another attachment
body = email.mime.Text.MIMEText("""Hello, how are you? I am fine.
This is a rather nice letter, don't you think?""")
msg.attach(body)

# PDF attachment
filename='simple-table.pdf'
fp=open(filename,'rb')
att = email.mime.application.MIMEApplication(fp.read(),_subtype="pdf")
fp.close()
att.add_header('Content-Disposition','attachment',filename=filename)
msg.attach(att)

# send via Gmail server
# NOTE: my ISP, Centurylink, seems to be automatically rewriting
# port 25 packets to be port 587 and it is trashing port 587 packets.
# So, I use the default port 25, but I authenticate. 
s = smtplib.SMTP('smtp.gmail.com')
s.starttls()
s.login('xyz@gmail.com','xyzpassword')
s.sendmail('xyz@gmail.com',['xyz@gmail.com'], msg.as_string())
s.quit()

关于python - 如何使用 SMTP 发送附件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1966073/

相关文章:

python - 预测排名的 ML 模型(列表的任意排序)

python - 如何在 Selenium WebDriver 中设置浏览器宽度和高度?

使用Python CMS创建像youtube这样的视频网站吗?

php 使用 sendmail 和 maildev 发送邮件需要 1 分钟以上

asp.net - 在 Asp.Net 中发送电子邮件时获取错误传输错误代码为 0x80040217

python - 如何在 discord.py 中使命令不区分大小写

email - GitHub 提交电子邮件

c# - 在 C# 中为多个 ID 读取多个 Outlook 电子邮件

java - 处理电子邮件服务器时如何处理代理?

vba - 在 Word VBA 中使用 .body 而不是 .htmlbody 将我的电子邮件正文的一部分设为粗体