今天优化了下之前定时任务时的发送邮件的代码。
添加了:
1、抄送
2、添加附件
使用1:
可以直接在下面这个文件的
if name == ‘main’:
里直接调用
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.utils import formataddr
from email.mime.application import MIMEApplication
def sendemail(sender, passwd, to_receiver: list, cc_receiver: list, title='邮件标题', content='邮件内容', attachment=''):
"""
QQ mail support only
sender,发送者
passwd,发送人qq邮箱授权码。这个授权码,是在qq邮箱里账户设置里设置的三方授权码。用pop3
to_receiver,接受人,可以传列表,给多个人发
cc_receiver,抄送人,可以传列表,给多个人发
title,邮箱标题
content,邮件内容
attachment,附件。传一个地址
"""
# 1、设置发送者
msg = MIMEMultipart() # MIMEMultipart类可以放任何内容
my_sender = sender
my_pass = passwd
# 接受者
my_to_receiver = to_receiver
my_cc_receiver = cc_receiver
receiver = my_to_receiver + my_cc_receiver
msg['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 == '': # 如果没传附件地址,就直接略过
pass
else:
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("smtp.qq.com", 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@qq.com'
passwd_main = 'XXX' #这个授权码,是在qq邮箱里账户设置里设置的三方授权码。用pop3,就是Python脚本中登录邮箱时的密码,而不是你平时登录邮箱时的那个密码
to_receiver_main = ['XXX@qq.com']
CC_receiver_main = ['XXX1@qq.com']
title_main = '2022年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 sendemail
sender = 'XXX@qq.com'
passwd = 'XXX'
to_receiver = ['XXX@qq.com']
CC_receiver = ['XXX123@qq.com']
title = '2022年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,查看邮箱接收情况。
邮件发送和接受成功。结束