美文网首页Python
Python_发送邮件的模块

Python_发送邮件的模块

作者: blade_he | 来源:发表于2018-09-07 17:47 被阅读1次

支持有附件的Email发送模块

"""
@version: 0.1
@author: Blade He
@license: Morningstar 
@contact: blade.he@morningstar.com
@site: 
@software: PyCharm
@file: emailutil.py
@time: 2018/9/7 15:59
"""
import os
import traceback
from email.header import Header
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
import smtplib
from email.mime.multipart import MIMEMultipart


def send_email(smtp_server,
               username,
               password,
               from_addr,
               to_addr,
               cc_addr,
               subject,
               content,
               content_type,
               attachfile,
               port=587):
    # 邮件发送和接收人配置
    msg = MIMEMultipart()
    msg['From'] = from_addr # 显示的发件人
    msg['To'] = to_addr
    if len(cc_addr.strip()) > 0:
        msg['Cc'] = cc_addr
    msg['Subject'] = Header(subject, 'utf-8')  # 显示的邮件标题

    # 需要传入的路径
    r = os.path.exists(attachfile)
    if r is False:
        msg.attach(MIMEText('no file...', content_type, 'utf-8'))
    else:
        # 邮件正文是MIMEText:
        msg.attach(MIMEText(content.strip(), content_type, 'utf-8'))
        filepart = MIMEApplication(open(attachfile, 'rb').read())
        filepart.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachfile))
        msg.attach(filepart)
    try:
        server = smtplib.SMTP(smtp_server, port)
        # server.set_debuglevel(1)  # 用于显示邮件发送的执行步骤
        # server.ehlo()
        # 如果是一般的smtp发送邮件,可以把下面一句注释
        server.starttls()
        # server.ehlo()
        server.login(username, password)
        server.sendmail(from_addr, to_addr, msg.as_string())
        server.quit()
    except Exception as e:
        print("Error: unable to send email")
        traceback.print_exc()

相关文章

  • Python_发送邮件的模块

    支持有附件的Email发送模块

  • python学习(21)smtp发送邮件

    本文介绍python发送邮件模块smtplib以及相关MIME模块。smtplib用于生成邮件发送的代理,发送邮件...

  • Python邮件正文及附件解析

    email邮件解析作为比较基础的模块,用来收取邮件、发送邮件。python的mail模块调用几行代码就能写一个发送...

  • Python之发送邮件

    Python之发送邮件 使用SMTP模块发送邮件 发送HTML文件 发送带附件的文件 Django发送文件 各大邮...

  • 2020-04-11 python学习日志--收发邮件

    邮件收发的两个模块(module): email模块构建邮件 smtplib模块发送邮件 示意如下:流程图.png...

  • 2018-07-17

    发送邮件 django中内置了邮件发送功能,被定义在django.core.mail模块中,发送邮件需要使用SMT...

  • smtp服务器开启

    发送邮件 Django中内置了邮件发送功能,被定义在django.core.mail模块中。发送邮件需要使用SMT...

  • 2018-08-09

    发送邮件 首先我们导入 email 模块,该模块用来构造我们需要传输的邮件信息。从 email 模块中导入 MIM...

  • python爬虫---短信通知(二)

    发送邮件 首先我们导入 email 模块,该模块用来构造我们需要传输的邮件信息。从 email 模块中导入 MIM...

  • Python使用smtplib,email模块发邮件

    摘要:Python 模块依赖 Python发邮件需要依赖两个模块,smtplib主要负责发送邮件,和email主要...

网友评论

    本文标题:Python_发送邮件的模块

    本文链接:https://www.haomeiwen.com/subject/sczcgftx.html