发邮件的脚本

mail

下面是一个使用python2写的发e-mail的脚本,调用方式:python mail.py 目标邮箱 “title” “content”

#!/usr/bin/env python
#-*- coding: UTF-8 -*-
import os,sys
reload(sys)
sys.setdefaultencoding('utf8')
import getopt
import smtplib
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
from  subprocess import *

def sendqqmail(username,password,mailfrom,mailto,subject,content):
    gserver = 'smtp.qq.com'
    gport = 25

    try:
        # msg = MIMEText(unicode(content).encode('utf-8')) //如果发送的邮件有乱码,可以尝试把这行改成如下:
        msg = MIMEText(content,'plan','utf-8') 
        msg['from'] = mailfrom
        msg['to'] = mailto
        msg['Reply-To'] = mailfrom
        msg['Subject'] = subject

        smtp = smtplib.SMTP(gserver, gport)
        smtp.set_debuglevel(0)
        smtp.ehlo()
        smtp.login(username,password)

        smtp.sendmail(mailfrom, mailto, msg.as_string())
        smtp.close()
    except Exception,err:
        print "Send mail failed. Error: %s" % err


def main():
    to=sys.argv[1]
    subject=sys.argv[2]
    content=sys.argv[3]
##定义QQ邮箱的账号和密码,你需要修改成你自己的账号和密码
    sendqqmail('[email protected]','password','[email protected]',to,subject,content)

if __name__ == "__main__":
    main()

使用前先修改脚本最后的发件邮箱。

QQ邮箱(163邮箱也是)如果开启了授权码登录,password就不能写登陆密码了。否则调用脚本会报错:

smtplib.SMTPAuthenticationError: (535, b'Error: \xc7\xeb\xca\xb9\xd3\xc3\xca\xda\xc8\xa8\xc2\xeb\xb5\xc7\xc2\xbc\xa1\xa3\xcf\xea\xc7\xe9\xc7\xeb\xbf\xb4: http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256')

可以在邮箱设置中开启授权码,password写成授权码就可以完成第三方登陆。

发布了130 篇原创文章 · 获赞 31 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/qq_42334372/article/details/99624082