Django 发送邮件

1. 配置相关参数

如果用的是 阿里云的企业邮箱,则类似于下面:

在 settings.py 的最后面加上类似这些

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True   #是否使用TLS安全传输协议(用于在两个通信应用程序之间提供保密性和数据完整性。)
EMAIL_USE_SSL = False    #是否使用SSL加密,qq企业邮箱要求使用
EMAIL_HOST = 'smtp.163.com'   #发送邮件的邮箱 SMTP服务器,这里用了163邮箱
EMAIL_PORT = 25     #发件箱的SMTP服务器端口
EMAIL_HOST_USER = 'yeyuzuiniubi@163.com'    #发送邮件的邮箱地址
EMAIL_HOST_PASSWORD = 'lilei123'         #发送邮件的邮箱密码(这里使用的是授权码)

EMAL_FROM = 即速生鲜<yeyuzuiniubi@163.com>

 

对于163网易邮箱的修改

 

 

 

view函数:

from django.shortcuts import render,HttpResponse

from django.core.mail import send_mail
# send_mail的参数分别是  邮件标题,邮件内容,发件箱(settings.py中设置过的那个),##收件箱列表(可以发送给多个人),失败静默(若发送失败,报错提示我们)
def send(request):
    send_mail('吴双伟你好', '你好', 'yeyuzuiniubi@163.com',
    ['wsw000320@163.com'], fail_silently=False)
    return HttpResponse('ok')

 QQ邮箱修改如下:

1.开启POP3和SMTP服务

  

 2.使用提示的密保手机向指定的号码发送指定的内容来完成验证

3.发送成功后,显示出授权码,记住此授权码后点击保存设置

 #发送邮件配置


EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

EMAIL_HOST = 'smtp.qq.com'
EMALL_PORT = 25
#发送邮件的邮箱
EMALL_HOST_URL='574634801@QQ.COM'
#在邮箱中设置的客户端授权密码
EMALL_HOST_POSSWORD = '授权码'

EMAL_FROM = 即速生鲜<yeyuzuiniubi@163.com>
代码实例:
  

from django.core.mail import send_mail1


subject = "海马生鲜欢迎你"# 邮件标题

message = "how are you"  # 邮件正文

sender = settings.EMAIL_FROM  # 发件人

receiver = [email]  # 收件人

send_mail(subject, message, sender, receiver)

 

 

 

发送多个邮件:
ps:send_mail 每次发邮件都会建立一个连接,发多封邮件时建立多个连接。而 send_mass_mail 是建立单个连接发送多封邮件,所以一次性发送多封邮件时 send_mass_mail 要优于 send_mail。

 代码示例:

from django.core.mail import send_mass_mail
message1 = ('Subject here', 'Here is the message', 'from@examle.com', ['first@example.com', 'other@example.com'])
message2 = ('Another Subject', 'Here is another message', 'from@example.com', ['second@test.com'])
send_mass_mail((message1, message2), fail_silently=False)

 

在邮件中添加附件,发送 html 格式的内容

from django.conf import settings

from django.core.mail import EmailMultiAlternatives

 

 

from_email = settings.DEFAULT_FROM_EMAIL

# subject 主题 

#content 内容 

#to_addr 是一个列表,发送给哪些人

message= EmailMultiAlternatives(subject, content, from_email, [to_addr])

message.content_subtype = "html"

# 添加附件(可选)

message.attach_file('./twz.pdf')

 

# 发送

message.send()

 

 

 

 

 

 

原文地址:https://www.cnblogs.com/pythonyeyu/p/11318953.html