|
| 1 | +from email.mime.application import MIMEApplication |
| 2 | +from email.mime.multipart import MIMEMultipart |
| 3 | +import smtplib |
| 4 | +from email.mime.text import MIMEText |
| 5 | + |
| 6 | +def send_mail(username, passwd, recv, title, content, mail_host='smtp.126.com', port=465, file=None): |
| 7 | + ''' |
| 8 | + 发送邮件函数,默认使用163smtp |
| 9 | + :param username: 邮箱账号 xx@163.com |
| 10 | + :param passwd: 邮箱密码 |
| 11 | + :param recv: 邮箱接收人地址,多个账号以逗号隔开 |
| 12 | + :param title: 邮件标题 |
| 13 | + :param content: 邮件内容 |
| 14 | + :param mail_host: 邮箱服务器 |
| 15 | + :param port: 端口号 |
| 16 | + :return: |
| 17 | + ''' |
| 18 | + if file: |
| 19 | + msg = MIMEMultipart() |
| 20 | + |
| 21 | + # 构建正文 |
| 22 | + part_text = MIMEText(content) |
| 23 | + msg.attach(part_text) # 把正文加到邮件体里面去 |
| 24 | + |
| 25 | + # 构建邮件附件 |
| 26 | + part_attach1 = MIMEApplication(open(file, 'rb').read()) # 打开附件 |
| 27 | + part_attach1.add_header('Content-Disposition', 'attachment', filename=file) # 为附件命名 |
| 28 | + msg.attach(part_attach1) # 添加附件 |
| 29 | + else: |
| 30 | + msg = MIMEText(content) # 邮件内容 |
| 31 | + msg['Subject'] = title # 邮件主题 |
| 32 | + msg['From'] = username # 发送者账号 |
| 33 | + msg['To'] = recv # 接收者账号列表 |
| 34 | + smtp = smtplib.SMTP_SSL(mail_host, port=port) |
| 35 | + smtp.login(username, passwd) # 登录 |
| 36 | + smtp.sendmail(username, recv, msg.as_string()) |
| 37 | + smtp.quit() |
| 38 | + |
| 39 | +if __name__ == '__main__': |
| 40 | + for i in range(1, 103): |
| 41 | + file_name = "aa" + format(i, '0>3d') |
| 42 | + print(file_name + " is sending...") |
| 43 | + |
| 44 | + send_mail("", "", "", "", "", mail_host="", file=file_name) |
0 commit comments