码迷,mamicode.com
首页 > Web开发 > 详细

django中发送html邮件

时间:2014-12-02 17:35:36      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:shell

settings.py文件中添加配置:


EMAIL_HOST=‘smtp.163.com‘

EMAIL_HOST_USER=‘username@163.com‘

EMAIL_HOST_PASSWORD=‘password‘

EMAIL_USE_TLS = True


方法1:

# -*- coding: utf-8 -*-
from django.conf import settings
settings.configure()
from django.core.mail import send_mail
from django.conf.global_settings import EMAIL_HOST_USER

send_mail(‘hello‘,‘just a test!‘,EMAIL_HOST_USER,[‘收件人列表‘])


方法2:

# -*- coding: utf-8 -*-
from django.conf import settings
settings.configure()
from django.core.mail import EmailMessage
from django.conf.global_settings import EMAIL_HOST_USER

subject, from_email, to = ‘hello‘, EMAIL_HOST_USER, ‘[收件人列表]‘
html_content = "<p>This is an <font size=3 color=‘green‘><strong>important</strong></font> message.</p>"
msg = EmailMessage(subject, html_content, from_email, [to])
msg.content_subtype = ‘html‘
msg.send()


方法3:

# -*- coding: utf-8 -*-
from django.conf import settings
settings.configure()
from django.core.mail import EmailMultiAlternatives
from django.conf.global_settings import EMAIL_HOST_USER

subject, from_email, to = ‘hello‘, EMAIL_HOST_USER, ‘[收件人列表]‘
text_content = ‘This is an important message.‘
html_content = "<p>This is an <font size=3 color=‘green‘><strong>important</strong></font> message.</p>"
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()

可以看到以html显示的邮件:

bubuko.com,布布扣


——————————————————分割线————————————————


同时发送多封邮件:

# -*- coding: utf-8 -*-
from django.conf import settings
settings.configure()
from django.core.mail import EmailMessage,get_connection
from django.conf.global_settings import EMAIL_HOST_USER

connection = get_connection()
connection.open()
html_content1 = "<p><strong>important </strong>message 1.</p>"
html_content2 = "<p><strong>important </strong>message 2.</p>"
email1 = EmailMessage(‘Hello‘, html_content1, EMAIL_HOST_USER, [‘收件人1‘])
email2 = EmailMessage(‘Hello‘, html_content2, EMAIL_HOST_USER, [‘收件人2‘])
email1.content_subtype = ‘html‘
email2.content_subtype = ‘html‘
connection.send_messages([email1, email2])
connection.close()



参考:https://docs.djangoproject.com/en/1.6/topics/email/

django中发送html邮件

标签:shell

原文地址:http://dragonball.blog.51cto.com/1459915/1585434

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!