view函数中
from django.core.mail import EmailMultiAlternatives
from django.http import JsonResponse
def send_message(request):
result = {'state':'error', 'data':''} #定义一个字典,用来记录运行情况
try:
subject = '这是一个来自django的邮件' #主题
text_content = 'hello django' #text文本记录
html_content = '<p style="color:red">its easy to learn python, never give up</p>'#html文本
message = EmailMultiAlternatives(subject,text_content,'xxxxx@163.com',[xxxxx@qq.com])#参数分别是邮件标题,文本内容,寄件人地址,收件人地址
message.attach_alternative(html_content,'text/html')
message.send()
except Exception as e :
result['data'] = str(e) #发送失败记录错误
else:
result['state'] = 'success' #发送成功,记录成功
result['data'] = 'success'
finally:
return JsonResponse(result) #返回result信息
settings.py中加入
EMAIL_HOST_USER = 'xxxxxx@163.com' #寄件人地址
EMAIL_HOST_PASSWORD = 'xxxxx' #激活码,通过163邮箱设置中,自行设置
EMAIL_USE_SSL = True
EMAIL_HOST = 'smtp.163.com'
EMAIL_PORT = '994'
配置路由后,运行结果如下
之后就可以在邮箱中查看了