带有Python附件的动态电子邮件

时间:2019-04-25 22:00:56

标签: python-3.x email-attachments

我对Python还是很陌生,因此可以联系社区以获取有关使用python向动态收件人列表发送电子邮件的帮助

我有一个收件人列表文本文件,其中包含用户名,电子邮件地址和他们需要以以下格式作为电子邮件附件接收的pdf列表的信息

pdf列表将存储在目录中。

目标是在收件人文本文件中将文件发送给收件人。

收件人文本文件格式

用户名usernameemail.com testfile.pdf testfile2.pdf

username2 username2email.com testfile3.pdf

具有下面的代码,可以在文本文件中向收件人发送电子邮件,但是还需要帮助来附加适当的pdf文件。

import smtplib

from string import Template
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

MY_ADDRESS = '#Sender'sEmailAddress'
PASSWORD = '#Senderspassword'

def get_contacts(filename):
"""
Return two lists names, emails containing names and email addresses
read from a file specified by filename.
"""

names = []
emails = []

with open(filename, mode='r', encoding='utf-8') as contacts_file:
    for a_contact in contacts_file:
        names.append(a_contact.split()[0])
        emails.append(a_contact.split()[1])    
return names, emails

def read_template(filename):
"""
Returns a Template object comprising the contents of the 
file specified by filename.
"""

with open(filename, 'r', encoding='utf-8') as template_file:
    template_file_content = template_file.read()
return Template(template_file_content)

def main():
names, emails = get_contacts('recipientlist.txt') # read contacts
message_template = read_template('message.txt')

# set up the SMTP server
s = smtplib.SMTP(host='smtp.gmail.com', port=587)
s.starttls()
s.login(MY_ADDRESS, PASSWORD)

# For each contact, send the email:
for name, email, in zip(names, emails):
    msg = MIMEMultipart()       # create a message

    # add in the actual person name to the message template
    message = message_template.substitute(PERSON_NAME=name.title())

    # Prints out the message body for our sake
    print(message)

    # setup the parameters of the message
    msg['From']=MY_ADDRESS
    msg['To']=email
    msg['Subject']="This is TEST"

    # add in the message body
    msg.attach(MIMEText(message, 'plain'))

    # send the message via the server set up earlier.
    s.send_message(msg)
    del msg

# Terminate the SMTP session and close the connection
s.quit()

if __name__ == '__main__':
    main()

0 个答案:

没有答案