zoukankan      html  css  js  c++  java
  • Python(email 邮件收发)

    1、发送 html 文本内容的邮件

    # smtplib 负责发送邮件
    import smtplib
    # MIMEText 负责构造邮件内容
    from email.mime.text import MIMEText
    # Header 是用来构建邮件头的
    from email.header import Header
    
    smtpServer= "smtp.163.com"
    sender = "zhengying0813@163.com"
    passWord = "MDZWNINBZEDKXXX"
    receiver = "zhengying0813@163.com"
    subject = "Python email test"
    # 三个参数:第一个为文本内容,第二个 html 设置文本格式,第三个 utf-8 设置编码
    msg = MIMEText("<html><h1>你好!</h1></html>","html","utf-8")
    # 定义邮件主题
    msg["Subject"] = Header(subject,"utf-8")
    msg["From"] = Header(sender,"utf-8")
    msg["To"] = Header(receiver)
    
    smtp = smtplib.SMTP()
    smtp.connect(smtpServer)
    # 登录 SMTP 服务器
    smtp.login(sender,passWord)
    # msg.as_string() 把 MIMEText 变成 str 对象
    smtp.sendmail(sender,receiver,msg.as_string())
    smtp.quit()

     2、发送带附件的邮件

    import smtplib
    from email.mime.text import MIMEText
    from email.header import Header
    from email.mime.multipart import MIMEMultipart
    
    smtpServer= "smtp.163.com"
    sender = "zhengying0813@163.com"
    passWord = "MDZWNINBZEDKCXXX"
    receiver = "zhengying0813@163.com"
    subject = "Python email test"
    
    # 创建一个带附件的实例
    msg = MIMEMultipart()
    msg["Subject"] = Header(subject,"utf-8")
    msg["From"] = Header(sender,"utf-8")
    msg["To"] = Header(receiver)
    
    # log.txt 为报告文件
    file = open("log.txt","rb").read()
    att = MIMEText(file,"base64","utf-8")
    # 这里的 filename 定义邮件中显示什么名字
    att["Content-Disposition"] = 'attachment; filename="log.txt"'
    # 添加文件到邮件附件中去
    msg.attach(att)
    
    smtp = smtplib.SMTP()
    smtp.connect(smtpServer)
    smtp.login(sender,passWord)
    smtp.sendmail(sender,receiver,msg.as_string())
    smtp.quit()
  • 相关阅读:
    Linux-nmap
    MongoDb注意事项
    HTML如何转XTML
    Centos 64位 Install certificate on apache 即走https协议
    CentOS 下搭建部署独立SVN服务器全程详解(5.5)
    LNMP安装与配置
    64位CentOS 6.0下搭建LAMP环境
    Apache遇到的问题:APR not found
    超详细LAMP环境搭建
    偏方治百病
  • 原文地址:https://www.cnblogs.com/ZhengYing0813/p/12869963.html
Copyright © 2011-2022 走看看