from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils.html import strip_tags
subject, from_email, to = 'Subject', 'from@xxx.com', 'to@xxx.com'
html_content = render_to_string('mail_template.html', {'varname':'value'}) # render with dynamic value
text_content = strip_tags(html_content) # Strip the html tag. So people can see the pure text at least.
# create the email, and attach the HTML version as well.
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
如果需要为邮件设置动态电子邮件模板,请将电子邮件内容保存在数据库表中。
这是我在 database = 中保存为 HTML 代码的内容
<p>Hello.. \{\{ first_name }} \{\{ last_name }}. <br> This is an <strong>important</strong> \{\{ message }}
<br> <b> By Admin.</b>
<p style='color:red'> Good Day </p>
In your views:
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
def dynamic_email(request):
application_obj = AppDetails.objects.get(id=1)
subject = 'First Interview Call'
email = request.user.email
to_email = application_obj.email
message = application_obj.message
text_content = 'This is an important message.'
d = {'first_name': application_obj.first_name,'message':message}
htmly = FirstInterviewCall.objects.get(id=1).html_content #this is what i have saved previously in database which i have to send as Email template as mentioned above HTML code
open("partner/templates/first_interview.html", "w").close() # this is the path of my file partner is the app, Here i am clearing the file content. If file not found it will create one on given path.
text_file = open("partner/templates/first_interview.html", "w") # opening my file
text_file.write(htmly) #putting HTML content in file which i saved in DB
text_file.close() #file close
htmly = get_template('first_interview.html')
html_content = htmly.render(d)
msg = EmailMultiAlternatives(subject, text_content, email, [to_email])
msg.attach_alternative(html_content, "text/html")
msg.send()
from django.core.mail import EmailMultiAlternatives
subject, from_email, to = 'hello', 'from@example.com', 'to@example.com'
text_content = 'This is an important message.'
html_content = '<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()
from django.template.loader import render_to_string
from django.core.mail import EmailMessage
# import html message.html file
html_template = 'path/to/message.html'
html_message = render_to_string(html_template, { 'context': context, })
message = EmailMessage(subject, html_message, from_email, [to_email])
message.content_subtype = 'html' # this is required because there is no plain text email message
message.send()