通过谷歌应用程序与 Django 发送电子邮件时给电子邮件帐户一个名称

我通过谷歌应用程序向使用 Django 的用户发送电子邮件。

当用户收到来自 Django 应用程序的电子邮件时,它们来自: do_not_reply@domain.example

当查看收件箱中的所有电子邮件时,人们认为邮件的发件人是: do_not_replydo_not_reply@domain.example取决于所使用的电子邮件客户端

如果我使用浏览器和谷歌应用程序登录到那个“不要回复”的账户,然后给自己发一封电子邮件,这些邮件来自: Don't Reply <do_not_reply@domain.example>

因此,收件箱中显示的电子邮件发件人的名称是: Don't Reply

在 Django 中,是否有一种方法可以将“姓名”附加到用于发送电子邮件的电子邮件帐户?

我检查了姜戈的 mail.py,但没有找到解决方案 Http://code.djangoproject.com/browser/django/trunk/django/core/mail.py?rev=5548

使用:

  • 姜戈1.1
  • Python 2.6
  • Ubuntu 9.1
  • settings.EMAIL_HOST = smtp.gmail.com
30523 次浏览

I use this code to send through gmail smtp (using google apps). and sender names are OK

def send_mail_gapps(message, user, pwd, to):
import smtplib
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(user, pwd)
mailServer.sendmail(user, to, message.as_string())
mailServer.close()

You can actually use "Don't Reply <do_not_reply@domain.example>" as the email address you send from.

Try this in the shell of your Django project to test if it also works with gapps:

>>> from django.core.mail import send_mail
>>> send_mail('subject', 'message', "Don't Reply <do_not_reply@domain.example>", ['youremail@example.com'])

Apart from the send_mail method to send email, EmailMultiAlternatives can also be used to send email with HTML content with text content as an alternative.

try this in your project

from django.core.mail import EmailMultiAlternatives
text_content = "Hello World"
# set html_content
email = EmailMultiAlternatives('subject', text_content, 'Dont Reply <do_not_reply@domain.example>', ['youremail@example.com'])


email.attach_alternative(html_content, 'text/html')
email.send()

This will send mail to youremail@example.com with Don't Reply wil be displayed as name instead of email do_not_reply@domain.example.