使用django内置邮件模块发送邮件

Django内置的邮件模块为 django.core.mail.send_mail

settings.py中配置邮箱设置

EMAIL_HOST = "smtp.163.com" # 邮箱服务器
EMAIL_PORT = 25 # 端口
EMAIL_HOST_USER = '' # 用户名
EMAIL_HOST_PASSWORD = '' # 邮箱服务商给生成的SMTP令牌
EMAIL_FORM = ''  # 收件人看到的发件人

send_mail源码

def send_mail(subject, message, from_email, recipient_list,
              fail_silently=False, auth_user=None, auth_password=None,
              connection=None, html_message=None):
    """
    Easy wrapper for sending a single message to a recipient list. All members
    of the recipient list will see the other recipients in the 'To' field.

    If auth_user is None, use the EMAIL_HOST_USER setting.
    If auth_password is None, use the EMAIL_HOST_PASSWORD setting.

    Note: The API for this method is frozen. New code wanting to extend the
    functionality should use the EmailMessage class directly.
    """
    connection = connection or get_connection(
        username=auth_user,
        password=auth_password,
        fail_silently=fail_silently,
    )
    mail = EmailMultiAlternatives(subject, message, from_email, recipient_list, connection=connection)
    if html_message:
        mail.attach_alternative(html_message, 'text/html')

    return mail.send()

send_mail必需参数

参数 功能 备注
subject 邮件标题 字符串
message 邮件正文 字符串
from_email 邮件发送人 字符串
recipient_list 邮件接受者 必须是一个列表

示例代码

utils/email_send.py

from random import Random
from django.core.mail import send_mail

from users.models import EmailVerifyRecord
from YiwenOnline.settings import EMAIL_FORM


# 生成随机字符串
def random_str(random_length=8):
    str = ''
    # 生成字符串的可选字符串
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    length = len(chars) - 1
    random = Random()
    for i in range(random_length):
        str += chars[random.randint(0, length)]
    return str


# 发送注册邮件
def send_register_email(email, send_type="register"):
    # 发送之前先保存在数据库,到时候查询链接是否存在
    code = random_str(16)
    email_record = EmailVerifyRecord(code=code, email=email, send_type=send_type)
    email_record.save()

    # 定义邮件内容
    email_title = ''
    email_body = ''
    if send_type == 'register':
        email_title = 'YiWenOnline注册激活链接'
        email_body = '请点击下面的链接激活你的账号: http://127.0.0.1:8000/active/{0}'.format(code)

        # 使用django内置函数完成邮件发送
        send_status = send_mail(email_title, email_body, EMAIL_FORM, [email])

        # 发送成功
        if send_status:
            print('发送成功')

效果

posted @ 2020-12-31 10:24  一文g  阅读(183)  评论(0编辑  收藏  举报