python3.7发送邮件带附件

代码:

 1 # -*- coding: utf-8 -*-
 2 
 3 import smtplib, ssl
 4 from email.mime.text import MIMEText
 5 from email.mime.multipart import MIMEMultipart
 6 
 7 
 8 def send_email_with_custom_smtp(sender_email, receiver_email, server, port, usr, password, subject, text, html,
 9                                 annex_path):
10     # mail gun exception, switch to port 465
11     # see: https://stackoverflow.com/questions/57715289/how-to-fix-ssl-sslerror-ssl-wrong-version-number-wrong-version-number-ssl
12     if server == 'smtp.mailgun.org':
13         port = 465
14 
15     message = MIMEMultipart("alternative")
16     if annex_path is not None:
17         for k in annex_path:
18             attach = MIMEText(k['annexContent'], 'base64', 'utf-8')
19             attach["Content-Type"] = 'application/octet-stream'
20             attach.add_header('Content-Disposition', 'attachment', filename='{}'.format(k['annexName']))
21             message.attach(attach)
22     else:
23         pass
24     message["Subject"] = subject
25     message["From"] = sender_email
26     message["To"] = receiver_email
27 
28     # Turn these into plain/html MIMEText objects
29     part1 = MIMEText(text, "plain")
30     part2 = MIMEText(html, "html")
31 
32     # Add HTML/plain-text parts to MIMEMultipart message
33     # The email client will try to render the last part first
34     message.attach(part1)
35     message.attach(part2)
36 
37 
38     # Create a secure SSL context
39     context = ssl.create_default_context()
40     with smtplib.SMTP_SSL(server, port, context=context) as server:
41         if int(port) == 587:
42             server.starttls(context=context)
43         try:
44             server.login(usr, password)
45         except:
46             raise ValueError('登录失败,请检查邮箱用户名与密码(授权码)是否正确')
47         try:
48             server.sendmail(
49                 sender_email, receiver_email, message.as_string()
50             )
51             return '邮件发送成功。', True
52         except:
53             return '邮件发送失败', False

 

posted @ 2021-03-29 16:49  F·灬小人物  阅读(121)  评论(0编辑  收藏  举报