0%

python 发送带附件邮件

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
import smtplib
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.header import Header

def send_email(filename, message_type='html'):
# 第三方 SMTP 服务
mail_host = "smtp.xxx.xxx.xxx" # 设置服务器
mail_user = "name@xxx.xxx.xxx" # 发件邮箱
mail_pass = "xxxxxx" # 密码
receivers = ['name@xxx.xxx.xxx',] # 收件邮箱

sender = 'name@xxx.xxx.xxx' # 发件邮箱

message=filename # 邮件内容
header=filename # 发件人title
subject=filename # 邮件标题

part = MIMEText(message, message_type, 'utf-8')
message = MIMEMultipart()

message['From'] = Header(header, 'utf-8')
message['Subject'] = Header(subject, 'utf-8')
message.attach(part)

attachment=MIMEApplication(open(filename, 'rb').read())
attachment.add_header('Content-Disposition', 'attachment', filename=filename)
message.attach(attachment)

try:
smtpObj = smtplib.SMTP()
smtpObj.connect(mail_host, 25) # 25 为 SMTP 端口号
smtpObj.login(mail_user, mail_pass)
smtpObj.sendmail(sender, receivers, message.as_string())
print("邮件发送成功")
return True
except smtplib.SMTPException:
print("Error: 无法发送邮件")
return False

if __name__ == '__main__':
send_email('test.txt')