python 发送邮件

配置服务器和邮箱

mail_info.py

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

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

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