在Python中使用附件发送Mail时出错

时间:2018-05-17 08:27:00

标签: python python-3.x

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()

1 个答案:

答案 0 :(得分:0)

您可以尝试以下代码:

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