您的位置:首页 > 编程语言 > Python开发

python 使用Django 的 邮件模块 发送邮件

2014-02-26 17:48 836 查看
python 有自己的邮件模块 smtplib,但是Django对其进行了封闭,感觉更简单了,使用DJANGO 邮件模块,两三行代码就可以解决问题。

def sendMail(subject, message, to_list, attachments=None, cc=None):
"""
@subject: 邮件标题
@message:邮件内容,可以是html字符串
@to_list:是一个列表,接收邮件的用户列表,都是邮箱
@attachments附件
"""
from django.core.mail.message import EmailMessage
from django.core.mail import get_connection
from products.netMinWeb import settings

from_email = auth_user = settings.EMAIL_HOST_USER #从django配置,发送者的邮箱
auth_password = settings.EMAIL_HOST_PASSWORD    #从django配置,发送者的邮箱密码
headers = {                                                                  #邮件头
"Date": time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
}
connection = get_connection(username=auth_user, password=auth_password, fail_silently=False) #连接到发送者邮箱
emailMsg = EmailMessage(subject, message, from_email, to_list, connection=connection, attachments=None, headers=headers, cc=None)
emailMsg.content_subtype = "html" #文本内容类型,默认是“plain”
emailMsg.send()



DJANGO EmailMessage 类部分代码:

class EmailMessage(object):
"""
A container for email information.
"""
content_subtype = 'plain'
mixed_subtype = 'mixed'
encoding = None     # None => use settings default

def __init__(self, subject='', body='', from_email=None, to=None, bcc=None,
connection=None, attachments=None, headers=None, cc=None):
"""
Initialize a single email message (which can be sent to multiple
recipients).

All strings used to create the message can be unicode strings
(or UTF-8 bytestrings). The SafeMIMEText class will handle any
necessary encoding conversions.
"""
if to:
assert not isinstance(to, six.string_types), '"to" argument must be a list or tuple'
self.to = list(to)
else:
self.to = []
if cc:
assert not isinstance(cc, six.string_types), '"cc" argument must be a list or tuple'
self.cc = list(cc)
else:
self.cc = []
if bcc:
assert not isinstance(bcc, six.string_types), '"bcc" argument must be a list or tuple'
self.bcc = list(bcc)
else:
self.bcc = []
self.from_email = from_email or settings.DEFAULT_FROM_EMAIL
self.subject = subject
self.body = body
self.attachments = attachments or []
self.extra_headers = headers or {}
self.connection = connection

def get_connection(self, fail_silently=False):
from django.core.mail import get_connection
if not self.connection:
self.connection = get_connection(fail_silently=fail_silently)
return self.connection
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: