Python的SMTP邮件发送代码

来源:互联网 发布:出纳做账软件 编辑:程序博客网 时间:2024/05/09 11:53
闲来无事,研究了一下使用Python的SMTP发邮件,源码如下:
首先要确保开启客户端POP3/SMTP服务:以QQ邮箱为例,先进入自己的QQ邮箱:设置-账户-开启POP3/SMTP服务(会让你用手机发送一个短信,发送成功后会给你一个密码)上述得到的密码就是下面pwd密码
使用Python 3,PyCharm。
#!/usr/bin/env python# -*- coding: utf-8 -*-import getoptimport smtplibimport syssender = 'xxxxxxxxx@qq.com'  # 发送者邮箱# If there are more than one receiver, you need to ganerate a list.# receiver = ['a@xxxx','b@xxxx']receiver = ['xxxxxx@163.com']  # 接收者邮箱server = 'smtp.qq.com'  # 邮件服务器,即发送者邮箱所属的邮件服务器port = '587'  # 发送者邮件服务器端口pwd = 'xxxxxxxxxx'  # 发送者邮件登录密码(QQ邮箱是开始POP3/SMTP服务时,服务器返回的密码,登陆密码无效)COMMASPACE = ', '# Import the email modules we'll needfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.mime.image import MIMEImagefrom email.mime.base import MIMEBasefrom email import encodersdef usage():    usageStr = '''''Usage: SendEmail -c mail_content'''    print    usageStrdef main(argv):    # Get the Email content in the "-c" argv    try:        opts, args = getopt.getopt(argv, "c:")    except getopt.GetoptError:        usage()        sys.exit(2)    content = ''    for opt, arg in opts:        if opt == '-c':            content = arg    print    content    #设置文本信息    #场景1 只发送主题    # msg = MIMEText(content)#只发送主题    #msg['Subject'] = 'This is the subject    #msg['From'] = sender    #msg['To'] = COMMASPACE.join(receiver)    #场景2 发送主题和具体信息    msg = MIMEMultipart()    msg['Subject'] = 'This is the python smtp project'    body = "This is a test mail, please ignore!"    msg.attach(MIMEText(body, 'plain'))    msg['From'] = sender    msg['To'] = COMMASPACE.join(receiver)    #添加附件    filename = "D:\E-files\Python\sky.jpg"#要发送的文件    attachment = open(filename, 'rb')    part = MIMEBase('application', 'octet-stream')    # 这也可以: part = MIMEBase('application', 'pdf')    part.set_payload((attachment).read())    encoders.encode_base64(part)    part.add_header('Content-Disposition', 'attachment', filename=filename)    msg.attach(part)    #设置smtp    s = smtplib.SMTP(server, port)    s.ehlo()    s.starttls()    s.login(sender, pwd)    s.sendmail(sender, receiver, msg.as_string())    s.quit()if __name__ == "__main__":    main(sys.argv[1:])
0 0
原创粉丝点击