在Python中发送带有附件的邮件时出错

2024-04-24 08:24:42 发布

您现在位置:Python中文网/ 问答频道 /正文

import smtplib, os
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import formatdate
from email import encoders

os.chdir(path)


def send_mail(send_from,send_to,subject,text,files,server,port,username='',password='',isTls=True):
    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = send_to
    msg['Date'] = formatdate(localtime = True)
    msg['Subject'] = 'Test'
    msg.attach(MIMEText(text))

    part = MIMEBase('application', "octet-stream")
    part.set_payload(open("Olaf.xlsx", "rb").read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; 
    filename="Olaf.xlsx"')
    msg.attach(part)

    smtp = smtplib.SMTP('smtp.web.de', 587)
    smtp.starttls()
    smtp.login('test@test.de', 'pw')

在此部分发生错误:NameError:name'msg'未定义。但是怎么了? 我从这里得到了代码:add excel file attachment when sending python email

    smtp.sendmail('xy','xyz', msg.as_string())

    smtp.quit()

Tags: textfromimportsendosemailmsgsmtp
1条回答
网友
1楼 · 发布于 2024-04-24 08:24:42

您可以尝试以下代码:

import smtplib, os
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email import Encoders
from email.mime.text import MIMEText

emaillist=['to@gmail.com'] # Receipient email address
msg = MIMEMultipart('mixed')
msg['Subject'] = 'Arrest Warrent' # mail subject line
msg['From'] = 'xyz@gmail.com' # From email address
msg['To'] = ', '.join(emaillist)

part = MIMEBase('application', "octet-stream")

# Provide the path of the file to be attached in the mail
part.set_payload(open('C:'+os.sep+'Users'+os.sep+'abhijit'+os.sep+'Desktop'+os.sep+'WarrentDetails.txt', "rb").read())
Encoders.encode_base64(part)

part.add_header('Content-Disposition', 'attachment; filename="WarrentDetails.txt"')

msg.attach(part)
msg.add_header('To', msg['From'])
text = "Dear Sir, \n\n An arrest warrent has been generated due to XYZ reason by ZZZ complain.\n YOU MUST APPEAR IN PERSON TO RESOLVE THIS MATTER. \n\n Regards,\n FBI :)"
part1 = MIMEText(text, 'plain')
msg.attach(part1)

# provide SMTP details of the host and its port number
server = smtplib.SMTP_SSL("smtp.gmail.com",465)
# If the host supports TLS then enable the below 2 lines of code
# server.ehlo()
# server.starttls()

server.login("xyz@gmail.com", "password")

server.sendmail(msg['From'], emaillist , msg.as_string())

有关这方面的更多详细信息,请参见this blog。你知道吗

相关问题 更多 >