How do I attach separate PDF's to contact list email addresses using Python?

跟風遠走 提交于 2020-01-25 09:20:12

问题


I have written a script that sends individual emails to all contacts in an Excel table. The table looks like this:

Names Emails             PDF
Name1 Email1@email.com   PDF1.pdf 
Name2 Email2@email.com   PDF2.pdf

The code I have so far is as follows:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from string import Template

import pandas as pd

e = pd.read_excel("Contacts.xlsx")

emails = e['Email'].values
PDF = e['PDF'].values
print(emails, PDF)

server = smtplib.SMTP(host='smtp.outlook.com', port=587) 
server.starttls()
server.login('sender_email','sender_password')

msg = ("""
Hi there

Test message

Thankyou
""")

subject = "Send emails with attachment"

body = "Subject: {}\n\n{}".format(subject,msg)   
for emails in emails:
    server.sendmail('sender_email',emails,body)

print("Emails sent successfully")

server.quit()

Question: How can I look up the correct attachment (column 3) for each e-mail address (column 2) and attach it to the email using Python?


回答1:


I made a little changes , and make you sure the pdf field has the pdf path Edit:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from string import Template
import pandas as pd

#e = pd.read_csv("Contacts.csv")
e = pd.read_excel("Contacts.xlsx")
server = smtplib.SMTP(host='smtp.outlook.com', port=587)
server.starttls()
server.login('yourmail@mail.com','yourpass')

body = ("""
Hi there

Test message

Thankyou
""")
subject = "Send emails with attachment"
fromaddr='yourmail@mail.com'
#body = "Subject: {}\n\n{}".format(subject,msg)
#Emails,PDF
for index, row in e.iterrows():
    print (row["Emails"]+row["PDF"])
    msg = MIMEMultipart()
    msg['From'] = fromaddr
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))
    filename = row["PDF"]
    toaddr = row["Emails"]
    attachment = open(row["PDF"], "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)
    text = msg.as_string()
    server.sendmail(fromaddr, toaddr, text)
    #server.sendmail('sender_email',emails,body)

print("Emails sent successfully")

server.quit()


来源:https://stackoverflow.com/questions/58575615/how-do-i-attach-separate-pdfs-to-contact-list-email-addresses-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!