Python的SMTP邮件发送代码

闲来无事,研究了一下使用Python的SMTP发邮件,源码如下:
首先要确保开启客户端POP3/SMTP服务:
以QQ邮箱为例,先进入自己的QQ邮箱:设置-账户-开启POP3/SMTP服务(会让你用手机发送一个短信,发送成功后会给你一个密码)
上述得到的密码就是下面pwd密码

使用Python 3,PyCharm。
 
 
#!/usr/bin/env python
# -*- coding: utf-8 -*-


import getopt
import smtplib
import sys

sender = '[email protected]'  # 发送者邮箱
# If there are more than one receiver, you need to ganerate a list.
# receiver = ['a@xxxx','b@xxxx']
receiver = ['[email protected]']  # 接收者邮箱
server = 'smtp.qq.com'  # 邮件服务器,即发送者邮箱所属的邮件服务器
port = '587'  # 发送者邮件服务器端口
pwd = 'xxxxxxxxxx'  # 发送者邮件登录密码(QQ邮箱是开始POP3/SMTP服务时,服务器返回的密码,登陆密码无效)

COMMASPACE = ', '

# Import the email modules we'll need
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.base import MIMEBase
from email import encoders

def usage():
    usageStr = '''''Usage: SendEmail -c mail_content'''
    print
    usageStr


def 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:])

猜你喜欢

转载自blog.csdn.net/tecsai/article/details/56483290