300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > Python用QQ邮箱发送邮件 支持抄送和附件

Python用QQ邮箱发送邮件 支持抄送和附件

时间:2019-11-13 12:58:51

相关推荐

Python用QQ邮箱发送邮件 支持抄送和附件

今天优化了下之前定时任务时的发送邮件的代码。

添加了:

1、抄送

2、添加附件

使用1:

可以直接在下面这个文件的

ifname== ‘main’:

里直接调用

import smtplibfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom email.utils import formataddrfrom email.mime.application import MIMEApplicationdef sendemail(sender, passwd, to_receiver: list, cc_receiver: list, title='邮件标题', content='邮件内容', attachment=''):"""QQ mail support onlysender,发送者passwd,发送人qq邮箱授权码。这个授权码,是在qq邮箱里账户设置里设置的三方授权码。用pop3to_receiver,接受人,可以传列表,给多个人发cc_receiver,抄送人,可以传列表,给多个人发title,邮箱标题content,邮件内容attachment,附件。传一个地址"""# 1、设置发送者msg = MIMEMultipart() # MIMEMultipart类可以放任何内容my_sender = sendermy_pass = passwd # 接受者my_to_receiver = to_receivermy_cc_receiver = cc_receiverreceiver = my_to_receiver + my_cc_receivermsg['From'] = formataddr(('发送者', my_sender))msg['To'] = ",".join(my_to_receiver)msg['Cc'] = ",".join(my_cc_receiver)# 2、设置邮件标题msg['Subject'] = title# 3、邮件内容my_content = content # 邮件内容msg.attach(MIMEText(my_content, 'plain', 'utf-8')) # 把内容加进去# 4、添加附件fujian = attachment # 定义附件if fujian == '': # 如果没传附件地址,就直接略过passelse:my_att = MIMEApplication(open(fujian, 'rb').read()) # 用二进制读附件my_att.add_header('Content-Disposition', 'attachment', filename=('gbk', '', 'phone_section_result.xls'))msg.attach(my_att) # 添加附件# 5、发送邮件try:server = smtplib.SMTP_SSL("", 465)server.login(my_sender, my_pass)server.sendmail(my_sender, receiver, msg.as_string())print("邮件发送成功")server.quit()except Exception as n:print("Error: 无法发送邮件")print(n)if __name__ == '__main__':sender_main = 'XXX@'passwd_main = 'XXX' #这个授权码,是在qq邮箱里账户设置里设置的三方授权码。用pop3,就是Python脚本中登录邮箱时的密码,而不是你平时登录邮箱时的那个密码to_receiver_main = ['XXX@']CC_receiver_main = ['XXX1@']title_main = '3月29日'content_main = """hello everyone:留点时间留点空闲,领着孩子常回家看看。带上笑容带上祝愿,啦啦啦忘词啦。我说谢谢你,感谢有你,温暖了四季。感谢你,因为有你,把笑容传递。public class void main()1234567890"""attachment_main = ''sendemail(sender=sender_main,passwd=passwd_main,to_receiver=to_receiver_main,cc_receiver=CC_receiver_main,title=title_main,content=content_main)

使用2:

也可以在另外的文件里写代码调用。

例如:

1、将上边的代码保存一个文件,比如叫:send_mail_ex2.py

2、新建一个文件,名字随意。比如叫:t_import_sendmail.py

3、编辑t_import_sendmail.py

from send_mail_ex2 import sendemailsender = 'XXX@'passwd = 'XXX'to_receiver = ['XXX@']CC_receiver = ['XXX123@']title = '3月29日测试'content = """ 邮件内容 """attachment = ''sendemail(sender=sender,passwd =passwd,to_receiver=to_receiver,cc_receiver=CC_receiver,title=title,content=content,attachment=attachment)

4、运行t_import_sendmail.py,查看邮箱接收情况。

邮件发送和接受成功。结束

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。