python - 如何使用 Python 从 Outlook 帐户发送带有附件的邮件
问题描述
我试过下面的代码来发送附件,但文件没有发送,只有内容正在发送。请帮忙。
SERVER = "smtp.example.com"
FROM = "yourEmail@example.com"
TO = ["listOfEmails"] # must be a list
enter code here
SUBJECT = "Subject"
TEXT = "Your Text"
# Prepare actual message
message = """From: %s\r\nTo: %s\r\nSubject: %s\r\n\
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
DNSFile="abc.csv"
# Send the mail
import smtplib
msg = MIMEMultipart()
msg.attach(DNSFile)
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()## Heading ##
解决方案
我使用的代码是使用 Python 发送附件:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
## FILE TO SEND AND ITS PATH
filename = 'some_file.csv'
SourcePathName = 'C:/reports/' + filename
msg = MIMEMultipart()
msg['From'] = 'from@domain.com'
msg['To'] = 'to@domain.com'
msg['Subject'] = 'Report Update'
body = 'Body of the message goes in here'
msg.attach(MIMEText(body, 'plain'))
## ATTACHMENT PART OF THE CODE IS HERE
attachment = open(SourcePathName, 'rb')
part = MIMEBase('application', "octet-stream")
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
server = smtplib.SMTP('smtp.office365.com', 587) ### put your relevant SMTP here
server.ehlo()
server.starttls()
server.ehlo()
server.login('from@domain.com', 'password_here') ### if applicable
server.send_message(msg)
server.quit()
希望这对你有用。这对我来说就像一个魅力。
推荐阅读
- forms - Delphi - 动态创建的表单上不显示丰富的编辑
- c++ - 错误 C2664:无法将参数从初始化程序列表转换为 std:initializer 列表
- java - 在 Cucumber 6 中初始化 webdriver
- css - 如何根据媒体查询更改按钮的文本
- python - Selenium Chrome Webdriver 进程在本地工作但不在 Heroku 上
- algorithm - 从 Vec 构建一个 UrlTree
- ruby-on-rails - Ruby 用指定的链接替换 html 片段
- swift - SwiftUI,无法通过带有 PageTabViewStyle 的 URL 加载图像
- flutter - 我如何在颤动中水平和垂直居中文本字段
- android - 无法读取 FRIDA 中未定义的属性键