• 【python】smtp邮件发送


    纯文本:

    #!/usr/bin/env python3
    #coding: utf-8
    
    import smtplib
    from email.mime.text import MIMEText
    from email.header import Header
    
    sender = '***'    
    receiver = '***'    
    subject = 'python email test'    
    smtpserver = 'smtp.163.com'    
    username = '***'    
    password = '***' 
    
    msg=MIMEText(_text="你好",_charset='utf-8')#中文需参数‘utf-8’,单字节字符不需要
    msg['Subject'] = Header(subject, 'utf-8')
    msg['From']=sender
    msg["To"]=receiver
    smtp = smtplib.SMTP()
    smtp.connect('smtp.exmail.qq.com')
    smtp.login(username, password)
    smtp.sendmail(sender, receiver, msg.as_string())
    smtp.quit()
    

     HTML格式:

    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email.mime.image import MIMEImage
    
    sender = '***'
    receiver = '***'
    subject = 'python email test'
    smtpserver = 'smtp.163.com'
    username = '***'
    password = '***'
    
    msgRoot = MIMEMultipart()
    msgRoot['Subject'] = 'test message'
    
    msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.<br><img src="cid:image1"><br>good!','html','utf-8')
    msgRoot.attach(msgText)
    
    fp = open('e:\1.jpg', 'rb')
    msgImage = MIMEImage(fp.read())
    fp.close()
    
    msgImage.add_header('Content-ID', '<image1>')
    msgRoot.attach(msgImage)
    
    smtp = smtplib.SMTP()
    smtp.connect('smtp.exmail.qq.com')
    smtp.login(username, password)
    smtp.sendmail(sender, receiver, msgRoot.as_string())
    smtp.quit()
    

     附件邮件:

    #coding: utf-8    
      
    import smtplib    
    from email.mime.multipart import MIMEMultipart    
    from email.mime.text import MIMEText    
    from email.mime.image import MIMEImage    
        
    sender = '***'    
    receiver = '***'    
    subject = 'python email test'    
    smtpserver = 'smtp.163.com'    
    username = '***'    
    password = '***'    
        
    msgRoot = MIMEMultipart('related')    
    msgRoot['Subject'] = 'test message'    
        
    #构造附件    
    att = MIMEText(open('h:\python\1.jpg', 'rb').read(), 'base64', 'utf-8')    
    att["Content-Type"] = 'application/octet-stream'    
    att["Content-Disposition"] = 'attachment; filename="1.jpg"'    
    msgRoot.attach(att)    
                
    smtp = smtplib.SMTP()    
    smtp.connect('smtp.163.com')    
    smtp.login(username, password)    
    smtp.sendmail(sender, receiver, msgRoot.as_string())    
    smtp.quit()
    

      

  • 相关阅读:
    列表,字典,元组,集合内置方法
    数据类型内置方法(1)
    if判断与while、for循环语句
    与用户交互、格式化输出、基本运算符
    执行python程序的两种方式
    # 操作系统与编程语言分类
    drf框架2-序列化与反序列化
    drf框架1
    前端-vue路由传参、axios前后台交互、cookie设置
    前端-vue的配置和使用
  • 原文地址:https://www.cnblogs.com/paulwinflo/p/5018536.html
Copyright © 2020-2023  润新知