python 发送邮件

配置服务器和邮箱

mail_info.py

1
2
3
4
5
6
mail_host = 'smtp.yeah.net'
mail_user = 'mail_name'
mail_pass = 'mail_password'

sender = 'mail_name@yeah.net'
receivers = ['target@mail.com']

发送邮件

mail_trans.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from .mail_info import *
import smtplib
from email.mime.text import MIMEText

def mail_text_send(title, text):
message = MIMEText(text, 'plain', 'utf-8')
message['Subject'] = title
message['From'] = sender
message['To'] = receivers[0]

try:
smtpObj = smtplib.SMTP()
# connect host
smtpObj.connect(mail_host, 25)
# login host
smtpObj.login(mail_user, mail_pass)
# send
smtpObj.sendmail(sender, receivers, message.as_string())
# quit
smtpObj.quit()
return True
except smtplib.SMTPException as e:
return False

主程序调用

main.py

1
2
from mail_trans import *
mail_text_send('title', 'hello world!')