今天突然想试试Django的邮件功能,便去查了一下。
Django发送邮件极其简单,它依赖于settings.py中的EMAIL参数。
在settings.py文件中加入:
EMAIL_HOST = ‘smtp.gmail.com’
EMAIL_PORT = ’25′
EMAIL_HOST_USER = ‘[email protected]’
EMAIL_HOST_PASSWORD = ‘password’
EMAIL_USE_TLS = True
EMAIL_PORT = ’25′
EMAIL_HOST_USER = ‘[email protected]’
EMAIL_HOST_PASSWORD = ‘password’
EMAIL_USE_TLS = True
用的Gmail的SMTP服务,也可以换自己的邮件服务器,现在就可以自定义一个sendmail函数了:
from django.core.mail import EmailMessage
from django.template import loader
from settings import EMAIL_HOST_USER
def send_html_mail(subject, html_content, recipient_list):
msg = EmailMessage(subject,
html_content,
EMAIL_HOST_USER,
recipient_list)
msg.content_subtype = “html”
msg.send()
from django.template import loader
from settings import EMAIL_HOST_USER
def send_html_mail(subject, html_content, recipient_list):
msg = EmailMessage(subject,
html_content,
EMAIL_HOST_USER,
recipient_list)
msg.content_subtype = “html”
msg.send()
recipient_list是邮件List,函数支持HTML代码。
试用一下这个函数函数:
send_html_mail(‘subject’,'contents’,['[email protected]'])
结果,邮件发送是成功了,但那速度慢的无法忍受,页面一直卡着,想了一下使用多线程应该能解决:
from threading import Thread
thread = Thread(target=send_html_mail,
args=(‘subject’,
‘contents’,
['[email protected]']))
thread.start()
thread = Thread(target=send_html_mail,
args=(‘subject’,
‘contents’,
['[email protected]']))
thread.start()
测试一下,果然不错。。。
