Python发送邮件

最近一个需求是使用Python自带的smtplib模块发送邮件,以下便是代码部分。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart

def send_mail(title, contents, receivers, path, filename):
mail_host = "smtp.163.com" # 设置服务器
mail_user = "***@163.com" # 用户名
mail_pass = "***" # 口令
sender = '***@163.com' # 和mail_user保持一致

# 创建一个带附件的实例
message = MIMEMultipart()
message['From'] = sender
message['To'] = ','.join(receivers)
message['Cc'] = sender

subject = 'Python发送邮件'
message['Subject'] = Header(subject, 'utf-8')

# 邮件正文内容
message.attach(MIMEText(contents, 'plain', 'utf-8'))

# 构造附件
attach_file = MIMEText(open(path, 'rb').read(), 'base64', 'utf-8')
attach_file["Content-Type"] = 'application/octet-stream'
# filename自定义 下面是实现附件可带中文
attach_file.add_header('Content-Disposition', 'attachment', filename='{}'.format(Header(filename, 'utf-8')))
# attach_file["Content-Disposition"] = f'attachment; filename={filename}'
message.attach(attach_file)

try:
result = True
errors = ''
smtpObj = smtplib.SMTP_SSL(mail_host, 465)
smtpObj.login(mail_user, mail_pass)
smtpObj.sendmail(sender, receivers, message.as_string())

except Exception as error:
# 捕捉全部异常
result = False
errors = error

return result, errors

代如果不合理请留言指正。

知识就是财富
如果您觉得文章对您有帮助, 欢迎请我喝杯水!