python发送邮件

简介: 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="附件名",
    )
相关文章
|
3月前
|
存储 搜索推荐 数据安全/隐私保护
python实战讲解之使用Python批量发送个性化邮件
python实战讲解之使用Python批量发送个性化邮件
|
5月前
|
Python
python实现发送邮件demo
python实现发送邮件demo
36 1
|
5月前
|
Unix 数据安全/隐私保护 Python
python自动生成Excel表格数据并发送邮件案例
python自动生成Excel表格数据并发送邮件案例
|
6月前
|
数据安全/隐私保护 Python
python 发送邮件demo
python 发送邮件demo
|
2月前
|
存储 安全 计算机视觉
用 Python 脚本实现电脑唤醒后自动拍照 截屏并发邮件通知
用 Python 脚本实现电脑唤醒后自动拍照 截屏并发邮件通知
|
3月前
|
存储 Shell API
Python 自动化指南(繁琐工作自动化)第二版:十八、发送电子邮件和短信
Python 自动化指南(繁琐工作自动化)第二版:十八、发送电子邮件和短信
57 0
|
3月前
|
移动开发 Python HTML5
Python办公自动化【发送普通邮件、发送HTML邮件、发送附件邮件-smtplib、批量发送邮件-smtplib、发送邮件-zmail】(八)-全面详解(学习总结---从入门到深化)
Python办公自动化【发送普通邮件、发送HTML邮件、发送附件邮件-smtplib、批量发送邮件-smtplib、发送邮件-zmail】(八)-全面详解(学习总结---从入门到深化)
41 0
|
8月前
|
Python
Python发送邮件脚本
Python发送邮件脚本
35 0
|
5月前
|
人工智能 安全 程序员
使用 ChatGPT 帮助小学生编程入门系列之二:使用 Python 编程发送电子邮件
使用 ChatGPT 帮助小学生编程入门系列之二:使用 Python 编程发送电子邮件
55 0