Python批量發郵件--加附件/抄送

來源:互聯網
上載者:User

標籤:python

# !/usr/bin/env python# -*- coding: UTF-8 -*-import csvfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.mime.application import MIMEApplicationfrom email.utils import COMMASPACE, formatdatefrom email import encodersimport timedef send_mail(server, fro, to, subject, text, chao):    assert type(server) == dict    assert type(to) == list    msg = MIMEMultipart()    msg[‘From‘] = fro    msg[‘Subject‘] = subject    msg[‘To‘] = COMMASPACE.join(to)  # COMMASPACE==‘, ‘    msg[‘Cc‘] = chao  # COMMASPACE==‘, ‘    msg[‘Date‘] = formatdate(localtime=True)    msg.attach(MIMEText(text))    xlsxpart = MIMEApplication(open(‘附件.docx‘, ‘rb‘).read())    xlsxpart.add_header(‘Content-Disposition‘, ‘attachment‘, filename=‘附件.docx‘)    msg.attach(xlsxpart)    import smtplib    smtp = smtplib.SMTP(server[‘name‘], server[‘port‘])    smtp.ehlo()    smtp.starttls()    smtp.ehlo()    smtp.login(server[‘user‘], server[‘passwd‘])    smtp.sendmail(fro, to+[chao], msg.as_string())    smtp.close()if __name__ == ‘__main__‘:    server = {‘name‘: ‘xx.163.com‘, ‘user‘: ‘xxxxx‘, ‘passwd‘: ‘xxx‘, ‘port‘: 25}    fro = ‘xxxxxxxx‘    subject = ‘xxxxx‘    with open(‘1.csv‘, ‘U‘) as csvfile:        # reader = csv.DictReader(csvfile)        reader = csv.reader(csvfile)        l = []        for row in reader:            l.append(row)    print("開始")    for i in l:        name = i[0]        mail = i[2:10]        chao = i[1]        b = ‘‘‘        您好!        值此“八一”建軍節之際,祝願貴公司蓬勃發展,建軍節快樂!                                                                                                 ‘‘‘        a = "尊敬的{0}:".format(name)        text = a + b        while ‘‘ in mail:            mail.remove(‘‘)        to = mail        print(‘to‘, to, ‘ok‘, ‘chao‘, chao, ‘ok‘)        time.sleep(7)        send_mail(server, fro, to, subject, text, chao)



  1. csv 的格式

第一列是客戶名稱,第二列是抄送的人,第三列和後面的是要發送的人。


 msg[‘To‘] = COMMASPACE.join(to)  # COMMASPACE==‘, ‘    msg[‘Cc‘] = chao  # COMMASPACE==‘, ‘
    smtp.sendmail(fro, to+[chao], msg.as_string())

需要特別注意的是上面,抄送的是 1個人。


Cc 是指要抄送,要注意抄送的是一個人還是多個。如果是多個,需要按照to的格式。


本文出自 “何全” 部落格,請務必保留此出處http://hequan.blog.51cto.com/5701886/1953223

Python批量發郵件--加附件/抄送

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.