"官方文檔 1.11" 配置 簡易文本郵件 連接一次郵件伺服器發送多份不同的郵件 和 發送多媒體郵件 發送html模板郵件 ...
官方文檔 1.11
配置settings.py
# QQ郵箱為例, 其他郵箱對應的SMTP配置可查官方
EMAIL_HOST = "smtp.qq.com"
EMAIL_PORT = 465
EMAIL_HOST_USER = "*********@qq.com"
EMAIL_HOST_PASSWORD = "dzptkzrdxcembieg"
EMAIL_USE_SSL = True
EMAIL_FROM = "no-replay<********@qq.com>"
EMAIL_TO = ["**********@163.com", "**************@163.com"]
send_mail
簡易文本郵件
(subject, message, from_email, recipient_list)
from __future__ import absolute_import
import time
import os
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "BoYa.settings")
django.setup()
from django.core.mail import send_mail
from users.models import ContactInfo
from BoYa.settings import EMAIL_FROM, EMAIL_TO
def send_tip_email():
u = ContactInfo.objects.order_by("-id").first()
email_title = "有新的信息"
email_body = "UserName: {}, \nEmail: {}, \nPhone: {}, \nWebSite: {}, \n" \
"Message: {}".format(u.name, u.email, u.phone, u.website, u.message,
time.strftime("%Y-%m-%d %H:%M:%S"))
send_status = send_mail(email_title, email_body, EMAIL_FROM, ["[email protected]"])
return send_status #發送成功狀態碼為1
send_mass_mail()
連接一次郵件伺服器發送多份不同的郵件
message1 = ('Subject here', 'Here is the message', '[email protected]', ['[email protected]', '[email protected]'])
message2 = ('Another Subject', 'Here is another message', '[email protected]', ['[email protected]'])
send_mass_mail((message1, message2), fail_silently=False)
EmailMultiAlternatives
和 EmailMessage
發送多媒體郵件
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
import time
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "BoYa.settings")
django.setup()
from django.core.mail import EmailMultiAlternatives, EmailMessage, send_mail
from BoYa.settings import EMAIL_FROM, EMAIL_HOST_USER
subject, from_email, to = 'hello', EMAIL_FROM, '[email protected]'
text_content = 'This is an important message.'
html_content = '<h1>This is a test <a href="https://www.baidu.com">message</a></h1>' \
'<p>This is an <strong>important</strong> message.</p>'
# msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
# msg.attach_alternative(html_content, "text/html")
# msg.send()
msg = EmailMessage(subject, html_content, from_email, [to])
msg.content_subtype = "html" # Main content is now text/html
# msg.attach('email.py', '8888888888877777777777777777777')
msg.attach_file('./email_send.py')
msg.attach_file(r'C:\Users\Belick\Desktop\Stu\BoYa_Project\BoYa\requirements.txt')
msg.send()
發送html模板郵件
from django.template import Context, loader
from users.models import UserProfile
user = UserProfile.objects.all().first()
print user.username
context = {
'username': user.username,
'image_url': user.image,
} # 變數可以在/templates/test.html模板中使用
email_template_name = 'test.html'
t = loader.get_template(email_template_name)
mail_list = ['[email protected]',]
msg = EmailMultiAlternatives(subject, t.render(context), from_email, [to])
msg.attach_alternative(t.render(context), "text/html")
msg.send()