zoukankan      html  css  js  c++  java
  • smtplib与email模块(实现邮件的发送)

    SMTP是发送邮件的协议,Python内置对SMTP的支持,可以发送纯文本邮件、HTML邮件以及带附件的邮件。

    Python对SMTP支持有smtplib和email两个模块,email负责构造邮件,smtplib负责发送邮件。

    1、smtplib模块

    smtplib模块定义了一个简单的SMTP客户端,可以用来在互联网上发送邮件。

    定义的类有如下:

    class smtplib.SMTP([host[, port[, local_hostname[, timeout]]]])
    class smtplib.SMTP_SSL([host[, port[, local_hostname[, keyfile[, certfile[, timeout]]]]]])
    class smtplib.LMTP([host[, port[, local_hostname]]])

    还有一些已经定义好的异常
    exception smtplib.SMTPException
    exception smtplib.SMTPServerDisconnected
    exception smtplib.SMTPResponseException
    exception smtplib.SMTPSenderRefused
    exception smtplib.SMTPRecipientsRefused
    exception smtplib.SMTPDataError
    exception smtplib.SMTPConnectError
    exception smtplib.SMTPHeloError
    exception smtplib.SMTPAuthenticationError

    这么多已定义的类中,我们最常用的的还是smtplib.SMTP类用法:
      
    smtp实例封装一个smtp连接,它支持所有的SMTP和ESMTP操作指令,如果host和port参数被定义,则smtp会在初始化期间自动调用connect()方法,如果connect()方法失败,则会触发SMTPConnectError异常,timeout参数设置了超时时间。在一般的调用过程中,应该遵connetc()、sendmail()、quit()步骤。

    smtplib.SMTP提供的方法:

    SMTP.set_debuglevel(level):#设置是否为调试模式。默认为False,
    
    SMTP.connect([host[, port]]):#连接到指定的smtp服务器。参数分别表示smpt主机和端口。
    # 默认是本机的25端口。也可以写成hostname:port的形式。
    
     SMTP.docmd(cmd[, argstring]):#向smtp服务器发送指令。可选参数argstring表示指令的参数。
    
     SMTP.helo([hostname]) :#使用"helo"指令向服务器确认身份。相当于告诉smtp服务器“我是谁”。
    
     SMTP.has_extn(name):#判断指定名称在服务器邮件列表中是否存在。
     #出于安全考虑,smtp服务器往往屏蔽了该指令。
    
     SMTP.verify(address) :#判断指定邮件地址是否在服务器中存在。
     #出于安全考虑,smtp服务器往往屏蔽了该指令。
    
     SMTP.login(user, password) :#登陆到smtp服务器。
     #现在几乎所有的smtp服务器,都必须在验证用户信息合法之后才允许发送邮件。
    
     SMTP.sendmail(self, from_addr, to_addrs, msg, mail_options=[],
    rcpt_options=[])
    #发送邮件。 #这里要注意一下第三个参数,msg是字符串,表示邮件。 #我们知道邮件一般由标题,发信人,收件人,邮件内容,附件等构成,发送邮件的时候,要注意msg的格式。 #这个格式就是smtp协议中定义的格式。  SMTP.quit() :#断开与smtp服务器的连接,相当于发送"quit"指令。

    2、email模块

    emial模块用来处理邮件消息,其包括的类有:

        class email.mime.base.MIMEBase(_maintype, _subtype, **_params):#这是MIME的一个基类。一般不需要在使用时创建实例。其中_maintype是内容类型,如text或者image。_subtype是内容的minor type 类型,如plain或者gif。 **_params是一个字典,直接传递给Message.add_header()。
    
        class email.mime.multipart.MIMEMultipart([_subtype[, boundary[, _subparts[, _params]]]]:#MIMEBase的一个子类,多个MIME对象的集合,_subtype默认值为mixed。boundary是MIMEMultipart的边界,默认边界是可数的。
    
        class email.mime.application.MIMEApplication(_data[, _subtype[, _encoder[, **_params]]]):#MIMEMultipart的一个子类。
    
        class email.mime.audio. MIMEAudio(_audiodata[, _subtype[, _encoder[, **_params]]]): MIME音频对象
    
        class email.mime.image.MIMEImage(_imagedata[, _subtype[, _encoder[, **_params]]]):#MIME二进制文件对象。
    
        class email.mime.text.MIMEText(_text[, _subtype[, _charset]]):#MIME文本对象,其中_text是邮件内容,_subtype邮件类型,可以是text/plain(普通文本邮件),html/plain(html邮件),  _charset编码,可以是gb2312等等。
    
        class email.mime.message.MIMEMessage(_msg[, _subtype]):#具体的一个message实例,使用方法如下:
        msg=mail.Message.Message()    #一个实例 
        msg['to']='XXX@XXX.com'      #发送到哪里 
        msg['from']='YYY@YYYY.com'       #自己的邮件地址 
        msg['date']='2012-3-16'           #时间日期 
        msg['subject']='hello world'    #邮件主题 

    smtplib.SMTP

    1、利用smtplib.SMTP发送一份普通文本邮件

    import smtplib
    from email.mime.text import MIMEText
    
    sender = 'wxtysg@163.com'  # 发件人邮箱账号
    my_pass= 'gahghfh'  # 发件人邮箱授权码
    receiver="888888@qq.com" #接收人邮箱
    def mail():
        ret = True
        try:
            content = "hello world"# 邮件内容
            msg = MIMEText(content, 'plain', 'utf-8')
            msg['From'] = sender  #发件人邮箱账号
            msg['To']=receiver
            msg['Subject'] = "Python发送邮件测试"  # 邮件的主题
    #创建连接对象并连接到服务器
            server = smtplib.SMTP("smtp.163.com")# 发件人邮箱中的SMTP服务器,端口是25
            server.login(sender, my_pass)# 发件人邮箱账号、授权码
            server.sendmail(sender, receiver, msg.as_string())
            server.quit()  # 关闭连接
        except Exception as e: 
            ret = False
            print(e)
        return ret
    
    ret = mail()
    if ret:
        print("邮件发送成功")
    else:
        print("邮件发送失败")

      ps:使用标准的25端口连接SMTP服务器时,使用的是明文传输,发送邮件的整个过程可能会被窃听。要更安全地发送邮件,可以加密SMTP会话,实际上就是先创建SSL安全连接,然后再使用SMTP协议发送邮件

    smtplib.SMTP_SSL

    利用smtplib.SMTP_SSL发送qq邮件

    注意要:发送QQ邮件需建立SSL安全连接。故需将smtplib.SMTP() 改成了smtplib.SMTP_SSL()

    class smtplib.SMTP_SSL([host[, port[, local_hostname[, keyfile[, certfile[, timeout]]]]]])
      这是一个派生自SMTP的子类,通过SSL加密的套接字连接(使用此类,您需要使用SSL支持编译的套接字模块)。如果未指定主机,则使用“(本地主机)”。如果省略端口,则使用标准的SMTP-over-SSL端口(465)。 local_hostname和source_address与SMTP类中的含义相同。密钥文件和证书文件也是可选的 - 它们可以包含用于SSL连接的PEM格式的私钥和证书链文件。上下文也是可选的,可以包含SSLContext,是keyfile和certfile的替代方法;如果指定keyfile和certfile都必须为None。

    1、发送一个普通文本邮件

    QQ邮箱POP3 和 SMTP 服务器地址设置如下:

    邮箱POP3服务器(端口995)SMTP服务器(端口465或587)
    qq.com pop.qq.com smtp.qq.com

    注:
      1、SMTP服务器需要身份验证。
      2、如果是设置POP3和SMTP的SSL加密方式,则端口如下:
        1)POP3接收邮件服务器(端口995);
        2)SMTP发送邮件服务器(端口465或587)。

    另外,用qq邮件服务器发送邮件需要先到邮箱里设开启SMTP/POP3服务。然后获取授权码, 在代码中要填写的密码是这个授权码, 而不是邮箱密码!


    import
    smtplib from email.mime.text import MIMEText msg_from = '6666666@qq.com' # 发送方邮箱 passwd = 'aczbvlbtrsaadjda' # 填入发送方邮箱的授权码 msg_to = '888888@qq.com' # 收件人邮箱 mail_host="smtp.qq.com" #发送人邮件的stmp服务器 port= 465 #端口号 #邮件 subject = "python邮件测试" # 主题 content = "Hello World"# 正文 msg = MIMEText(content) msg['Subject'] = subject msg['From'] = msg_from msg['To'] = msg_to #创建连接对象并连接到服务器 s = smtplib.SMTP_SSL(mail_host,port) # 邮件服务器及端口号,SMTP_SSL默认使用465端口号,端口号可省略 # 登录服务器 s.login(msg_from, passwd) try: s.sendmail(msg_from, msg_to, msg.as_string()) print("发送成功") except s.SMTPException as e: print(e) print("发送失败") finally: s.quit()

    2、发送HTML格式的邮件

      在构造MIMEText对象时,把HTML字符串传进去,再把第二个参数由plain变为html就可以了:

    import smtplib
    from email.mime.text import MIMEText
    msg_from = '2419636244@qq.com'  # 发送方邮箱
    passwd = 'qfzgdumpeswjdjic'  # 填入发送方邮箱的授权码
    # tolist=["2419636231@qq.com","2419636244@qq.com"]
    msg_to = "2419636231@qq.com" # 收件人邮箱 ,可以一次发给多个人
    mail_host="smtp.qq.com" #服务器
    port= 465 #端口号
    #邮件
    subject = "python邮件测试"  # 主题
    content = """"
    <p>Python 邮件发送测试...</p>
    <p><a href="http://www.cnblogs.com/freely/">戳它</a></p>
    """#内容
    msg = MIMEText(content,"html",'utf-8')#三个参数:第一个为文本内容,第二个MIME的subtype,设置文本格式,传入'plain',最终的MIME就是'text/plain',第三个 utf-8 设置编码
    #plain 页面上原样显示这段代码
    msg['Subject'] = subject
    msg['From'] =  msg_from
    msg['To'] = msg_to
    #创建连接对象并连接到
    s = smtplib.SMTP_SSL(mail_host,port)  # 邮件服务器及端口号
    # 登录服务器
    s.login(msg_from, passwd)
    try:
        s.sendmail(msg_from,msg_to, msg.as_string())
        print("发送成功")
    except Exception as e:
        print(e)
        print("发送失败")
    finally:
        s.quit()

    附:如何获取授权码?

    1、登陆发送方邮箱

    2、开启服务

  • 相关阅读:
    有人向我反馈了一个bug
    java.lang.ClassNotFoundException: org.springframework.core.SpringProperties
    Maven pom文件提示Missing artifact org.springframework:spring-context-support:jar:3.2.2.RELEASE:compile
    在业务逻辑中如何进行数据库的事务管理。
    about to fork child process, waiting until server is ready for connections. forked process: 2676 ERROR: child process failed, exited with error number 100
    tomcat底层原理实现
    springmvc 动态代理 JDK实现与模拟JDK纯手写实现。
    纯手写SpringMVC架构,用注解实现springmvc过程
    数据库连接池原理 与实现(动脑学院Jack老师课后自己的练习有感)
    定时器中实现数据库表数据移动的功能,Exception in thread "Timer-0" isExist java.lang.NullPointerException定时器中线程报错。
  • 原文地址:https://www.cnblogs.com/freely/p/6859117.html
Copyright © 2011-2022 走看看