Simple send mail script sharing implemented in Python

  • 2020-04-02 14:19:48
  • OfStack

Recently some things need to monitor alarm email, and then on the Internet to find some materials, I wrote a simple email script, mainly using python's smtplib module, to share with you:


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# The import smtplib and MIMEText
import smtplib,sys
from email.mime.text import MIMEText
  
def send_mail(sub,content):
    #############
    # To whom? Over here 1 personal
    mailto_list=["wangwei03@jb51.net"]
    #####################
    # Set the server, username, password, and mailbox suffix
    mail_host="mail.gyyx.cn"
    mail_user="wangwei03@jb51.net"
    mail_pass="123456677890"
    mail_postfix="gyyx.cn"
    ######################
    '''''
    to_list: Sent to who
    sub: The theme
    content: content
    send_mail("aaa@126.com","sub","content")
    '''
    me=mail_user+"<"+mail_user+"@"+mail_postfix+">"
    msg = MIMEText(content,_charset='gbk')
    msg['Subject'] = sub
    msg['From'] = me
    msg['To'] = ";".join(mailto_list)
    try:
        s = smtplib.SMTP()
        s.connect(mail_host)
        s.login(mail_user,mail_pass)
        s.sendmail(me, mailto_list, msg.as_string())
        s.close()
        return True
    except Exception, e:
        print str(e)
        return False
if __name__ == '__main__':
    if send_mail(u' This is a python Test email ',u'python Send E-mail '):
        print u' Send a success '
    else:
        print u' Send failure '


Related articles: