Отправка электронного письма с приложением к НЕСКОЛЬКИМ людям - PullRequest
1 голос
/ 22 мая 2019

Я действительно новичок в отправке писем на 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 Ответ

1 голос
/ 22 мая 2019

Вы можете достичь этого с помощью 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()
...