从Csv文件中读取并使用附件将邮件发送给收件人

时间:2017-06-23 06:48:01

标签: python csv email

我有两个单独的python代码。 1是从CSV文件读取,另一个是发送带附件的电子邮件。我的主要目的是将两个代码分成1并发送附件的电子邮件,其收件人在CSV内。经过大量的谷歌搜索,我仍然没有设法让它工作,任何帮助将不胜感激:)。

- >这是在电子邮件中发送附件的代码:

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders

fromaddr = "noreply.vigilare@gmail.com"
toaddr = ("abc@xyz.com")

msg = MIMEMultipart()

msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "SUBJECT OF THE EMAIL"

body = "TEXT YOU WANT TO SEND"

msg.attach(MIMEText(body, 'plain'))

filename = "image.png"
attachment = open("/home/vigzm/image.png", "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)

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "Pas***rd")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()

- >这是从CSV文件中读取和发送电子邮件的代码:

#!/usr/bin/python

import csv
import smtplib
from email.mime.text import MIMEText
from email.Header import Header

def sendmail(info_list):
msg = MIMEText(info_list[2], "html", "utf-8")
msg['Subject'] = Header("Read and Send", "utf-8")
msg['From'] = "noreply.vigilare@gmail.com"
msg['To'] = info_list[2]
s = smtplib.SMTP("smtp.gmail.com")
s.ehlo()
s.starttls()
s.login("noreply.vigilare@gmail.com", "Pa****rd")
s.sendmail("Vignesh", info_list[2], msg.as_string())

def main():
with open("Test1.csv", "rb") as csvfile:
    msg_reader = csv.reader(csvfile)
    msg_reader.next()
    map(lambda x: sendmail(x), msg_reader)

if __name__ == "__main__":
    main()

0 个答案:

没有答案