I am currently trying to send emails via smtplib with the following code:
import smtplib
import email.utils
from email.mime.text import MIMEText
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo()
smtpserver.login('username@gmail.com', 'pwd')
msg['Subject'] = "subject line"
msg['From'] = 'newusername@gmail.com'
msg['To'] = 'friend@gmail.com'
smtpserver.sendmail(sender, recipients, msg.as_string())
When I do something like this, instead of the recipient getting an email from newusername@gmail.com
, they get it from username@gmail.com
, which was the email I used for authentication.
Is there a way to change this?
This is an intentional security feature in gmail, and other public mail servers, called SMTP AUTH.
Without this feature, anyone with a gmail address could send mail impersonating anyone else with a gmail address. I could send a message claiming to be from you, and the recipient would have no way of knowing it wasn't from you, and you'd have no way to prove it wasn't from you.
But it wouldn't matter anyway, because spammers would be sending so much more email with your address than you do that email addresses would be effectively meaningless, and the whole email system would fall apart. Which is what almost happened in the late 90s. Only a concerted campaign to require SMTP AUTH on all open submission servers, including blacklisting all mail from servers that didn't comply (even the ones that used POP-before-SMTP, IMAP-before-SMTP, IP/MAC verification, or other alternatives to SMTP AUTH) managed to keep the spammers from ruining everything.
Later, another security/anti-spam measure, called DKIM, was added, which gmail also uses: most servers will throw out any messages that isn't signed by the originating server, indicating that the server trusts that the message came from who it says it came from. Obviously, gmail isn't going to certify that a message came from newusername
when it actually came from username
.1 And, if they did, people who administer other servers would just blacklist gmail signatures are meaningless.
1. Unless they have some reason to trust that username
has the right to send mail as newusername
—corporate mail servers sometimes do have a feature like that, allowing you to configure things so, e.g., a secretary can send mail from his boss's address without having his boss's password.