• python学习(十四)python操作发送邮件(163邮箱)


    一、163邮箱
    1、先导入smtplib库来发送邮件,导入MIMEText库用来做纯文本的邮件模块
    2、准备发送邮件参数

    import smtplib
    from email.mime.text import MIMEText
    
    # 发送邮件相关参数
    smtpserver = 'smtp.163.com'         # 发件服务器
    port = 0                            # 端口
    sender = 'zhu1308331523@163.com'         # 发件人邮箱
    psw = '*******'                            # 发件人密码
    receiver = "214256271@qq.com"       # 接收人
    '''
    3、编写邮件主题和正文,正文用的html格式
    4、最后调用发件服务
    '''
    # 编辑邮件内容
    subject = '邮件主题'
    body = '<p>这是个发送邮件的正文</p>'  # 定义邮件正文为html
    msg = MIMEText(body, 'html', 'utf-8')
    msg['from'] = sender
    msg['to'] = "214256271@qq.com"
    msg['subject'] = subject
    # 发送邮件
    smtp = smtplib.SMTP()
    smtp.connect(smtpserver)    # 链接服务器
    smtp.login(sender, psw)     # 登录
    smtp.sendmail(sender, receiver, msg.as_string())  # 发送
    smtp.quit()             # 关闭

    可能出现的报错

    python smtplib.SMTPAuthenticationError: (535, b'Error: authentication failed')

    解决办法:163邮箱开启POP3/SMTP服务,163邮件会让我们设置客户端授权码代替发送的密码填写进入,就可以发送成功了

    二、带 附件的发送邮件

    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    
    # 发送邮件相关参数
    smtpserver = 'smtp.163.com'         # 发件服务器
    port = 0                            # 端口
    sender = 'zhu1308331523@163.com'         # 发件人邮箱
    psw = '******'                            # 发件人密码
    receiver = "214256271@qq.com"       # 接收人
    # 邮件标题
    subjext = 'python发送附件邮件'
    # 获取附件信息
    with open('result.html', "rb") as f:
        body = f.read().decode()
    message = MIMEMultipart()
    # 发送地址
    message['from'] = sender
    message['to'] = receiver
    message['subject'] = subjext
    # 正文
    body = MIMEText(body, 'html', 'utf-8')
    message.attach(body)
    # 同一目录下的文件
    att = MIMEText(open('result.html', 'rb').read(), 'base64', 'utf-8') 
    att["Content-Type"] = 'application/octet-stream'
    # filename附件名称
    att["Content-Disposition"] = 'attachment; filename="result.html"'
    message.attach(att)
    smtp = smtplib.SMTP()
    smtp.connect(smtpserver)    # 链接服务器
    smtp.login(sender, psw)     # 登录
    smtp.sendmail(sender, receiver, message.as_string())  # 发送
    smtp.quit()             # 关闭

    三、发送多个收件人

    '''
    1.上面都是发给一个收件人,那么如何一次发给多个收件人呢?只需改两个小地方
    2.把receiver参数改成list对象,单个多个都是可以收到的
    3、msg["to"]这个参数不能用list了,得先把receiver参数转化成字符串
    '''
    # receiver = ["214256271@qq.com", "130@qq.com"]
    # message['to'] = ";".json(receiver)

     

  • 相关阅读:
    [AX]AX2012开发新特性outer join中使用QueryFilter
    [AX]AX2012开发新特性表继承
    docker环境安装
    poj 3469
    poj 1187
    poj 1159
    poj 2135
    poj 1273
    poj 1458
    poj 1141
  • 原文地址:https://www.cnblogs.com/jiliangceshi/p/13220082.html
Copyright © 2020-2023  润新知