zoukankan      html  css  js  c++  java
  • 【python】用SMTP模块发送带附件的邮件

    第一篇博客!参考链接

    在书上看了用SMTP模块发邮件,试过之后发现并没有什么用。163邮箱开启了SMTP服务后,登陆了发送的时候却被拒收了。

    找了前人的资料,发现被过期的教程害死了。

    以下代码有效:

    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    from email.mime.image import MIMEImage
    #全部为python内置,不需要安装第三方模块
    receivers = ["receivers@163.com"]
    sender = "sender@163.com"
    mail_pass = "password"
    mail_subject = "python发送邮件测试"         # 邮件的标题
    mail_context = "这是邮件内容"
    
    
    msg = MIMEMultipart()
    msg["From"] = sender  # 发件人
    msg["To"] = ";".join(receivers)  # 收件人
    msg["Subject"] = mail_subject   # 邮件标题
    # 邮件正文
    msg.attach(MIMEText(mail_context, 'plain', 'utf-8'))
    #图片附件
    #不同的目录下要写全文件路径
    with open('test.jpg','rb') as picAtt:
        msgImg = MIMEImage(picAtt.read())
        msgImg.add_header('Content-Disposition', 'attachment', filename='你.jpg')
        #msgImg.add_header('Content-ID', '<0>')
        #msgImg.add_header('X-Attachment-Id', '0')
        msg.attach(msgImg)
    # 构造附件
    att = MIMEText(open('test.txt', "rb").read(), "base64", "utf-8")
    att["Content-Type"] = "application/octet-stream"
    # 附件名称为中文时的写法
    att.add_header("Content-Disposition", "attachment", filename=("gbk", "", "测试结果.txt"))
    # 附件名称非中文时的写法
    # att["Content-Disposition"] = 'attachment; filename="test.html")'
    msg.attach(att)
    
    try:
        # 启动网易SMTP服务,端口465
        smtpObj = smtplib.SMTP_SSL('smtp.163.com', 465)
        # 登陆账号
        smtpObj.login('sender@163.com', 'your_password')
        # 发送
        smtpObj.sendmail(sender, receivers, msg.as_string())
        print('Success!')
        # 退出登录
        smtpObj.quit()
    except smtplib.SMTPException as e:
        print(e)

    如果不需要附件,删除附件的代码块就行。

    注:密码最好不保存在代码中,而是使用时输入

  • 相关阅读:
    【Android平台安全方案】の #00-请不要在外部存储(SD卡)加密存储的敏感信息
    本学习笔记TCP/IP传输协议
    iOS_23_undress Girl
    uva 1560
    IOS开发-Swift新语言初见
    39个让你受益的HTML5教程
    ubuntu12.04管理员账户登录不了桌面,仅仅能客人会话登录
    怎样使用SetTimer MFC 够具体
    ArcGIS API for Silverlight 编辑Geometry
    几种更新(Update语句)查询的方法
  • 原文地址:https://www.cnblogs.com/to-red/p/9745964.html
Copyright © 2011-2022 走看看