How do I send email from a user's email address with Django?

孤街浪徒 提交于 2020-01-16 11:25:30

问题


I'd like to send email to third parties on behalf of users. The key is for the user's email to show up as the "from:" email.

I've tried using send_mail with the user's email as the from_email, but to no avail. When I used gmail's servers to send the message, the third party sees the EMAIL_HOST_USER as the "from:" email. And when I tried using namecheap's mail server, I got SMTPRecipientsRefused: {u'<to email>': (553, '5.7.1 <from email>: Sender address rejected: not owned by user <EMAIL_HOST_USER>')}.

If possible, I'd like to avoid asking for their password as well.


回答1:


Short answer: You can't do that.

Back in the old days, mail servers used to be quite relaxed about posting mail whenever anyone asked them to, but then SPAM happened and people realised that it was actually quite important to check that the person sending an email is actually the person whose address appears in the From: header.

There are now several mechanisms in place that make it very difficult to spoof a sender email address. These include:

  1. Sender Policy Framework (SPF): An email validation system that works by placing restrictions on the IP addresses authorised to send email from a particular email address. If you try sending email from an IP address not associated with the legitimate owner of an email address, your mail will be rejected.

  2. DomainKeys Identified Mail (DKIM): A method for confirming that emails claiming to have originated from a particular mail server really did originate from that server.

  3. Mail transfer agent restrictions: These days, most MTAs are configured to only accept emails from people who it already knows. (This is why you're seeing a Sender address rejected: not owned by user error message).

Instead, your best option — essentially your only option — is to put your own email address in the From: header, and send the email from your own mail server. If you want the reply to go to someone else, add a Reply-To: header containing their email address.




回答2:


If you are using Exchange, you might be able to use a library such as Exchangelib, in which the author seems to have been inspired by some of Django's design decisions. Unfortunately, it does look like you will still need to ask for the user's password. I'm going to be looking into this further later on, and since I use LDAP authentication to the Django project, perhaps there is some way to use that to authenticate to the email server, but I have my skepticism.

See this question: https://serverfault.com/questions/546255/sending-email-with-python-django-through-microsoft-exchange-imap



来源:https://stackoverflow.com/questions/20293986/how-do-i-send-email-from-a-users-email-address-with-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!