哪有什么岁月静好,不过是有人替你负重前行!

django实现发送邮件

一、发送普通文本邮件

1、settings.py中的设置

# 发送邮件
# 发送邮件设置
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = False   # 是否使用TLS安全传输协议
EMAIL_USE_SSL = True    # 是否使用SSL加密,qq企业邮箱要求使用
# SMTP地址
EMAIL_HOST = 'smtp.qq.com'
# SMTP端口
EMAIL_PORT = 465
# 自己的邮箱
EMAIL_HOST_USER = '776265xxxx@qq.com'
# 自己的邮箱授权码,非密码
EMAIL_HOST_PASSWORD = 'qvsvaxxxxxxxxx'
EMAIL_SUBJECT_PREFIX = '[迎风而来的博客]'

2、视图函数实现发送文本

from django.shortcuts import render, HttpResponse
from django.core.mail import send_mail


def send_email(request):
    """
    发送邮件
    :param request:
    :return:
    """
    send_mail(subject='发送邮件的标题',
              message='发送邮件的内容',
              from_email='776265233@qq.com',  #发送者邮箱
              recipient_list=['1971956593@qq.com'], # 接收者邮箱可以写多个
              fail_silently=False)
    return HttpResponse('邮件发送成功')

二、发送带有附件的邮件

1、settings.py中的设置

# 发送邮件
# 发送邮件设置
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = False   # 是否使用TLS安全传输协议
EMAIL_USE_SSL = True    # 是否使用SSL加密,qq企业邮箱要求使用
# SMTP地址
EMAIL_HOST = 'smtp.qq.com'
# SMTP端口
EMAIL_PORT = 465
# 自己的邮箱
EMAIL_HOST_USER = '776265xxxx@qq.com'
# 自己的邮箱授权码,非密码
EMAIL_HOST_PASSWORD = 'qvsvabxxxxxxxxxx'
EMAIL_SUBJECT_PREFIX = '[迎风而来的博客]'

2、视图函数实现发送附件

import os
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from email.header import make_header


def send_accessory_email(request):
    subject = '报告邮件'  # 邮件主题
    text_content = '这是一封重要的报告邮件.'  # 邮件文本内容
    html_content = '<p>这是一封<strong>重要的报告邮件</strong>.</p>'  # 邮件主题内容样式
    from_email = settings.EMAIL_HOST_USER    # 发送者邮箱
    receive_email_addr = ["19719xxxxxx@qq.com"]  # 接收者邮箱可以写多个
    msg = EmailMultiAlternatives(subject, text_content, from_email, receive_email_addr)
    msg.attach_alternative(html_content, "text/html")
    # 发送附件
    file_path = r"C:\文件\附件.xlsx"   # 发送附件的文件路径
    text = open(file_path, 'rb').read()
    file_name = os.path.basename(file_path)
    # 对文件进行编码处理
    b = make_header([(file_name, 'utf-8')]).encode('utf-8')
    msg.attach(b, text)   # 传入文件名和附件
    msg.send()
    if msg.send():
        return HttpResponse('邮件发送成功')
    else:
        return HttpResponse('邮件发送成功')

 

posted @ 2020-06-10 14:52  迎风而来  阅读(1402)  评论(0编辑  收藏  举报
/*吸附球*/