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

    qq邮箱设置中 生成授权码作为密码

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    import smtplib
    from email.mime.text import MIMEText
    from email.utils import formataddr
     
    my_sender='450092375@qq.com'    # 发件人邮箱账号
    my_pass = 'iurfjdzxmpvscaah'              # 发件人邮箱密码
    my_user='450092375@qq.com'      # 收件人邮箱账号,我这边发送给自己
    def mail():
        ret=True
        try:
            msg=MIMEText('填写邮件内容','plain','utf-8')
            msg['From']=formataddr(["FromRunoob",my_sender])  # 括号里的对应发件人邮箱昵称、发件人邮箱账号
            msg['To']=formataddr(["FK",my_user])              # 括号里的对应收件人邮箱昵称、收件人邮箱账号
            msg['Subject']="菜鸟教程发送邮件测试"                # 邮件的主题,也可以说是标题
     
            server=smtplib.SMTP_SSL("smtp.qq.com",port= 465)  # 发件人邮箱中的SMTP服务器,端口是25
            server.login(my_sender, my_pass)  # 括号中对应的是发件人邮箱账号、邮箱密码
            server.sendmail(my_sender,[my_user,],msg.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
            server.quit()  # 关闭连接
        except Exception as e:  # 如果 try 中的语句没有执行,则会执行下面的 ret=False
            ret=False
            print ("send email failed %s"%e)
        return ret
     
    ret=mail()
    if ret:
        print("邮件发送成功")
    else:
        print("邮件发送失败")

     带附件

    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    from email.header import Header
     
    sender = 'from@runoob.com'
    receivers = ['450092375@qq.com']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
    my_sender='450092375@qq.com'    # 发件人邮箱账号
    my_pass = 'iurfjdzxmpvscaah'              # 发件人邮箱密码
    #创建一个带附件的实例
    message = MIMEMultipart()
    message['From'] = Header("菜鸟教程", 'utf-8')
    message['To'] =  Header("测试", 'utf-8')
    subject = 'Python SMTP 邮件测试'
    message['Subject'] = Header(subject, 'utf-8')
     
    #邮件正文内容
    message.attach(MIMEText('这是菜鸟教程Python 邮件发送测试……', 'plain', 'utf-8'))
     
    # 构造附件1,传送当前目录下的 test.txt 文件
    att1 = MIMEText(open('test.txt', '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_SSL("smtp.qq.com",port= 465)
        smtpObj.login(my_sender, my_pass)
        smtpObj.sendmail(my_sender, receivers, message.as_string())
        print ("邮件发送成功")
    except smtplib.SMTPException:
        print ("Error: 无法发送邮件")
  • 相关阅读:
    小波变换的引入,通俗易懂
    Leetcode 437. Path Sum III
    Leetcode 113. Path Sum II
    Leetcode 112 Path Sum
    Leetcode 520 Detect Capital
    Leetcode 443 String Compression
    Leetcode 38 Count and Say
    python中的生成器(generator)总结
    python的random模块及加权随机算法的python实现
    leetcode 24. Swap Nodes in Pairs(链表)
  • 原文地址:https://www.cnblogs.com/dzh1990/p/8514850.html
Copyright © 2011-2022 走看看