dubkoidragon
dubkoidragon

Reputation: 21

Sending an alias(spoof) for the 'from' e-mail using python smtplib

I am using python 3.4.3 to send e-mail, and at this time I will be needing the e-mail to be sent under an alias. The account is a gmail account, but I need to be able to put whatever I want as the spoof(alias) 'From' e-mail. I have looked quite hard at how to do this and have had very little luck. Given the amount of threads I've looked at and the actuality that I haven't gotten a workable answer shows the lack of discussion about this specific topic. I hope it's not just that this is something so very easy that everyone but me knows how to do it.

I should mention that I am on a windows 10 machine, but have access to a Ubuntu, and Windows 7 machine as well.

import smtplib

fromreal = '[email protected]'
fromshow = '[email protected]'
toaddy = ['[email protected]', '[email protected]']
subject = ' test'
body = 'This is the body test'

content = '''\
From: %s
To: %s
Subject: %s
%s
''' % (fromshow, ', '.join(toaddy), subject, body)

server = 'smtp.gmail.com'
port = 587

mail = smtplib.SMTP(server, port)

mail.ehlo()
mail.starttls()
mail.login(fromreal, 'password')
try:
    mail.sendmail(fromshow, toaddy, content)
    print('E-mail sent.')
except:
    print('E-mail not sent.')

mail.close()

Upvotes: 2

Views: 9043

Answers (2)

Easy_Israel
Easy_Israel

Reputation: 841

Your code is fine,

Google prevents you from setting an alias email that not belongs to you. That's why you need to set the alias in your gmail account. To do this go to https://mail.google.com/ -> settings -> (see all settings) -> Accounts -> Send mail as: -> add another email address.

Validate the email address and then you can set your alias as used in your code.

If you get an SMTPAuthenticationError (534, b'5.7.9 Application-specific password required. ...) you should follow the link to set an app-password instead of your real password.

Upvotes: 0

PascalVKooten
PascalVKooten

Reputation: 21451

You can use yagmail to send an alias (not changing to the fake email, but at least the alias):

import yagmail
# first is "from" arg; using a dictionary you can give an alias as value
yag=yagmail.SMTP({fromreal:'fakealias'}, 'password') 
yag.send(toaddy, subject, body)

How nice it is to have 3 lines instead of 30 ;)

Install using pip install yagmail.

Read more about a lot of other features on the github page.

Among other things, you could use "passwordless" scripts (no need for password in script), really easy to send HTML, inline images and attachments!

Full disclosure: I'm the developer/maintainer of yagmail.

Upvotes: 6

Related Questions