如何使用Python从Outlook帐户发送带有附件的邮件

  • 本文关键字:Python 何使用 Outlook python
  • 更新时间 :
  • 英文 :


我尝试了以下代码来发送附件,但是文件没有发送,只有内容正在发送。 请帮忙。

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: %srnTo: %srnSubject: %srn
%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()

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

以防其他人在 2022 年发现自己在这里; 以下是 Outlook.com 更新的 IMAP、POP 和 SMTP 设置:

  • IMAP 服务器名称:outlook.office365.com
  • IMAP 端口:993
  • IMAP加密方法:TLS
  • POP 服务器名称:outlook.office365.com
  • POP 端口:995
  • POP 加密方法:TLS
  • SMTP 服务器名称:smtp-mail.outlook.com
  • SMTP 端口:587
  • SMTP加密方法:STARTTLS

最新更新