Django通过内置send_mail发送邮件的代码

2022-03-11 00:00:00 django send

Django下使用smtp以及Django 发送邮件例子,本范例使用了django自带的send_mail进行邮件发送

"""
作者:皮蛋编程(https://www.pidancode.com)
创建日期:2022/3/25
功能描述:Django发送邮件的代码
"""
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponseRedirect
from django.http import HttpResponse


def send_email(request):
    subject = request.POST.get('subject', '主题:皮蛋编程(www.pidancode.com)')  # 发送的邮件主题
    message = request.POST.get('message', 'it \'s time to go home')  # 发送的消息
    from_email = request.POST.get('from_email', '******')  # 发件人邮箱
    to_email = request.POST.get('to_email', '××××××')
    # 收件人的邮箱
    if subject and message and from_email:
        try:
            send_mail(subject, message, from_email, [to_email])  # 最后一个参数是收件人列表,可发送至多人
        except BadHeaderError:
            return HttpResponse('非法头信息.')
        return HttpResponseRedirect('/buy/')
    else:
        return HttpResponse('Make sure all fields are entered and valid.')

相关文章