django发送邮件(email)

settings.py配置

1 '''邮件配置'''
2 EMAIL_HOST = 'smtp.163.com'
3 EMAIL_PORT = 25
4 EMAIL_HOST_USER = 'xxxx@163.com'
5 EMAIL_HOST_PASSWORD = 'xxx'
6 UserEmail='xxx<xxxx@163.com>'

发送方法

from django.core.mail import EmailMessage
from django.template import loader
from email.Utils import formatdate


"""普通邮件"""
def common_email(title,content,target_email):
    
    if not isinstance(target_email,(tuple,list)):
        target_email=[target_email]
        
    date = formatdate(localtime = True)
    msg = EmailMessage(title, content, settings.UserEmail, target_email, headers = {'Date': date})
    result = msg.send(fail_silently = True)
    return result


"""页面邮件"""
def html_email(subject,html,para,recipient_list):
    
    if not isinstance(recipient_list,(tuple,list)):
        recipient_list = [recipient_list]
    
    html_content = loader.render_to_string(html,para)
    date = formatdate(localtime = True)
    msg = EmailMessage(subject, html_content, settings.UserEmail, recipient_list, headers = {'Date': date})
    msg.content_subtype = "html"
    
    return msg.send(fail_silently = True)

也可用python直接调用django方法发送邮件,添加代码:

from django.conf import settings

settings.configure(
                   EMAIL_HOST = 'smtp.163.com',
                   EMAIL_HOST_USER = 'xxx@163.com',
                   EMAIL_HOST_PASSWORD = 'xxx',
                   UserEmail='测试 <xxx@163.com>',
                   EMAIL_PORT = 25,
                   TEMPLATE_DIRS=[
                                    '/home/xx/workspace/',
                                 ],
                   )

  

posted @ 2014-07-21 11:02  to_jh  阅读(210)  评论(0编辑  收藏  举报