python发送邮件

  • python发邮件方法

    import smtplib
    from email.header import Header
    from email.mime.application import MIMEApplication
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    
    def send_mail(subject, body, to, cc=None, file_path=None, file_name=None):
        """
        发送邮件
        :param subject: 邮件主题
        :param body: 邮件内容
        :param to: 收件人
        :param cc: 抄送人
        :param file_path: 附件绝对路径地址
        :param file_name: 附件名称
        :return:
        """
        # 发件人
        sender = "xxxx@163.com"
        message = MIMEMultipart()
        # 发件邮箱
        message['From'] = sender
        # 配置收件人
        message['To'] = ";".join(to)
        # 配置抄送人
        message['Cc'] = ";".join(cc)
        # 配置邮件主题
        message['Subject'] = Header(subject, 'utf-8')
    
        message.attach(MIMEText(body, _subtype="html", _charset='utf-8'))
        # 添加附件
        if file_path and file_name:
            excel_data = MIMEApplication(open(file_path.encode('utf-8'), 'rb').read())
            excel_data.add_header('Content-Disposition', 'attachment', filename=u'{}'.format(file_name))
            message.attach(excel_data)
    
        try:
            smtp_server = smtplib.SMTP_SSL("smtp.163.com", 465)
            smtp_server.login(sender, "emailpassword")
            smtp_server.sendmail(sender, to + cc, message.as_string())
            smtp_server.quit()
            print("邮件发送成功, {}".format(body))
        except smtplib.SMTPException:
            print("邮件发送失败, {}".format(body))
  • 调用方法

    send_mail(
        subject="邮件主题", 
        body="发送内容", 
        to=["收件人<xxxx@163.com>", "收件人2<xxxx2@163.com>"], 
        cc=["抄送人<xxxx3@163.com>"],
        file_path="文件路径", 
        file_name="附件名",
    )
上一篇:pytest使用


下一篇:Django跟某几个字段去重MySQL