zoukankan      html  css  js  c++  java
  • python发送邮件

    python发送邮件(无附件)

    =======================================================

    #!/usr/bin/env python
    #coding=utf-8

    import smtplib
    from email.mime.text import MIMEText
    from email.header import Header

    def sendmail():
    #第三方服务(发件人的信息)
      mail_host = '设置服务器:端口'
      mail_user = '发件人邮箱的用户名'
      mail_pass = '发件人邮箱的密码'
      receivers = ['接收的邮箱']

    #邮件主题
      message = MIMEText('你好,邮件测试','plain','utf-8')
      message['From'] = Header('发件人的中文名称','utf-8')
      message['To'] = Header('收件人的中文名称','utf-8')

    # 邮件标题
      subject = 'Python 邮件测试'
      message['Subject'] = Header(subject,'utf-8')

      try:
        smtpObj = smtplib.SMTP(mail_host)
        smtpObj.ehlo()
        smtpObj.starttls()
        smtpObj.login(mail_user,mail_pass)
        smtpObj.sendmail(mail_user,receivers,message.as_string())
        smtpObj.quit()
        print "邮件发送成功"
      except smtplib.SMTPException:
        print "Error 无法发送邮件"

    if __name__ == '__main__':
      sendmail()

    ========================================================

    python发送邮件(有附件)

    #!/usr/bin/env python
    #coding=utf-8

    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    from email.header import Header

    def sendmail():
    #第三方服务
      mail_host = '设置服务器:端口'
      mail_user = '发件人邮箱的用户名'
      mail_pass = '发件人邮箱的密码'

      receivers = ['接收的邮箱'] 

      message = MIMEMultipart()
      message['From'] = Header('发件人邮箱的中文名称','utf-8')
      message['To'] = Header('收件人邮箱的中文名称','utf-8')

      #邮件标题  

      subject = 'Python 邮件测试'
      message['Subject'] = Header(subject,'utf-8')

    # 邮件正文内容
      message.attach(MIMEText('这是菜鸟教程Python 邮件发送测试……','plain','utf-8'))

    # 构造附件1,传送当前目录下的 bj.log 文件
      att1 = MIMEText(open('bj.log', 'rb').read(), 'base64', 'utf-8')
      att1["Content-Type"] = 'application/octet-stream'
    # 这里的filename可以任意写,写什么名字,邮件中显示什么名字(也就是附件的名称)
      att1["Content-Disposition"] = 'attachment; filename="test.txt"'
      message.attach(att1)

      try:
        smtpObj = smtplib.SMTP(mail_host)
        smtpObj.ehlo()
        smtpObj.starttls()
        smtpObj.login(mail_user,mail_pass)
        smtpObj.sendmail(mail_user,receivers,message.as_string())
        smtpObj.quit()
        print "邮件发送成功"
      except smtplib.SMTPException:
        print "Error 无法发送邮件"

    if __name__ == '__main__':
      sendmail()

  • 相关阅读:
    收藏的博客
    MVC 之 System.Web.Optimization找不到引用
    SQL Server 之 附加数据库出现“ 拒绝访问 ”
    Android Studio 之 环境搭建
    PD 之 连接数据库并导出数据及生成PDM文件
    Windows 之 可以Ping通服务器但无法使用服务器连接的共享打印机
    JQuery 之 在数据加载完成后才自动执行函数
    JavaScript 之 动态加载JS代码或JS文件
    JQuery 之 动态加载JS或JS文件
    JavaScript 之 解码类似eval(function(p,a,c,k,e,d){}))的JavaScript代码
  • 原文地址:https://www.cnblogs.com/happlyp/p/6246901.html
Copyright © 2011-2022 走看看