如何使用Python将单独的PDF附加到联系人列表电子邮件地址? [英] How do I attach separate PDF's to contact list email addresses using Python?

查看:102
本文介绍了如何使用Python将单独的PDF附加到联系人列表电子邮件地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个脚本,该脚本将单个电子邮件发送到Excel表中的所有联系人.该表如下所示:

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

问题:如何查找每个电子邮件地址(第2列)的正确附件(第3列),然后使用Python将其附加到电子邮件中?

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?

推荐答案

我做了一些更改,并确保pdf字段具有pdf路径

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

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

这篇关于如何使用Python将单独的PDF附加到联系人列表电子邮件地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆