首页 > 解决方案 > 如何使用 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

解决方案


我使用的代码是使用 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()

希望这对你有用。这对我来说就像一个魅力。


推荐阅读