向多个人发送带有附件的电子邮件

时间:2019-05-22 17:06:47

标签: python smtplib

对于使用python发送电子邮件,我真的很陌生。我可以发送带附件的单个电子邮件,不带附件的多个电子邮件-但是我的代码无法发送多个电子邮件和附件。

    msg = MIMEMultipart()
    fromaddr = email_user
    toaddr = ["email"]
    cc = ["email2"]
    bcc = ["email3"]

    subject = "This is the subject"
    body = 'Message for the email' 
    msg = "From: %s\r\n" % fromaddr+ "To: %s\r\n" % toaddr + "CC: %s\r\n" % ",".join(cc) + "Subject: %s\r\n" % subject + "\r\n" + body
    toaddr = toaddr + cc + bcc
    msg.attach(MIMEText(body,'plain'))
    filename ="excelfile.xlsx" 
    attachment=open(filename,'rb')
    part = MIMEBase('application','octet-stream')
    part.set_payload((attachment).read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition',"attachment; filename= "+filename)
    msg.attach(part)
    text = msg.as_string()
    server = smtplib.SMTP('smtp.gmail.com',587)
    server.starttls()
    server.login(email_user,email_password)
    server.sendmail(fromaddr, toaddr, message) 
    server.quit()

我收到以下错误... AttributeError:'str'对象没有属性'attach'

1 个答案:

答案 0 :(得分:1)

您可以借助MIMEMultipart和MIMEText(此处为文档:https://docs.python.org/3.4/library/email-examples.html)来实现此目的

基本上,您只需使用以下内容创建附件:

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

并将其附加到电子邮件中:

msg.attach(part)

此处显示完整代码:

import smtplib                                                                          #import libraries for sending Emails(with attachment)
#this is to attach the attachment file
from email.mime.multipart import MIMEMultipart
#this is for attaching the body of the mail
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

server = smtplib.SMTP('smtp.gmail.com', 587)                                            #connects to Email server
server.starttls()
server.user="your@email" 
server.password="yourpassw"
server.login(server.user, server.password)                                              #log in to server

#creates attachment
msg=MIMEMultipart()
part = MIMEBase('application', "octet-stream")
part.set_payload(open("attachment.txt", "rb").read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="attachment.txt"')

#attach the attachment
msg.attach(part)

#attach the body
msg.attach(MIMEText("your text"))

#sends mail with attachment
server.sendmail(server.user, ["user@1", "user@2", ...], msg=(msg.as_string()))
server.quit()