I'm trying to send emails with my gmail account using python. I've already read many questions here and around the Internet, but none of them solved my problem.
The code that I'm using is the following (thanks to rosettacode), which is very similar to many other code snippets that can be found about this topic:
def sendemail(from_addr, to_addr_list, cc_addr_list,
subject, message,
login, password,
smtpserver='smtp.gmail.com:587'):
header = 'From: %s\n' % from_addr
header += 'To: %s\n' % ','.join(to_addr_list)
header += 'Cc: %s\n' % ','.join(cc_addr_list)
header += 'Subject: %s\n\n' % subject
message = header + message
server = smtplib.SMTP(smtpserver)
server.ehlo()
server.starttls()
server.ehlo()
server.login(login,password)
problems = server.sendmail(from_addr, to_addr_list, message)
server.quit()
return problems
My problem is during the login phase. It returns the following error message:
SMTPAuthenticationError: (534, '5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbsMX\n5.7.14 Z4_8qLgwTbhS2CwFvVApFvRfpIS1Vbbfun6gHcf0D6jgSQ-ixMn79mf3AivveTs9IhYsgq\n5.7.14 pmrp157H4Vmk6-ybAC9u2d2lNMYyy5pdmociqeSxBBwFGEPGJKHKdJpSocx86gzG-im6V-\n5.7.14 hsOeMKiJRAuGZjHUprEwj8oABwLzWQ8vEzovpXk79M-i8cnFseW-PNLxLlsK21WaLHLKmZ\n5.7.14 Ll3tEgQ> Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/bin/answer.py?answer=78754 dc8sm25406976wib.7 - gsmtp')
I followed the suggested link and I found this answer, but I don't know if it could be the solution.
So, what's the problem? My account's settings? My code?
Google has recently tightened their security. Application that use username/password directly have been deactivated. All users are still able to reactivate these less secure application in their security settings as you have been reading in the link you gave in your question. This is the only solution at this point.
The alternative would be to use an other SMTP server for sending.
The error message you quote says
[..] Please log in via your web browser and then try again.
5.7.14 Learn more at
5.7.14 https://support.google.com/mail/bin/answer.py?answer=78754
This was already discussed in server send emails using gmail smtp gets alerts.
So I'd say that your code is fine and you're dealing with a Google-specific security mechanism.
You could enable Google's 2-step authentication and then generate an application-specific password for your script. I do the same (I also have similar code as you) and it works fine.
Related
I'm trying to send emails with smtplib and they seem to be delivering fine. The only problem is that DKIM fails and the mails usually go straight to the spam folder.
DKIM is enabled on my shared hosting (host is a2hosting, if that helps) and the process works fine when sending individual emails with Thunderbird, and DKIM passes, suggesting that the problem lies on my end.
I even tried using dkimpy to explicitly sign the emails using the private key but I still get dkim=fail under ARC-Authentication-Results.
Some posts and answers I referred to suggested "logging in" as the solution but I am already logging in using SMTP.login() and as I mentioned earlier, the emails are being sent.
An answer I referred to mentioned that it is the server's job to sign the email and it's worth mentioning that the raw email output includes the DKIM signature, even without explicitly signing it with dkimpy, indicating that the server is signing as expected.
But the problem remains that DKIM fails affecting the email deliverability, and the raw output does not provide any details as to why DKIM failed for the domain.
I use the following code snippet to send an email
msg = MIMEMultipart()
msg['From'] = 'myemail#mydomain.tld'
msg['To'] = 'someemail#gmail.com'
msg['Subject'] = "Subject"
msg.attach(MIMEText("SomeText", "plain"))
s = smtplib.SMTP_SSL("mydomain.tld:465")
s.login("myemail#mydomain.tld", "mypassword")
s.sendmail("myemail#mydomain.tld", 'someemail#gmail.com',msg.as_string())
I tried signing the message as follows
headers = ["To", "From", "Subject"]
with open("cert.pem") as fh:
dkim_private = fh.read()
sig = dkim.sign(
message=msg.as_string().encode("ascii"),
selector=str(dkim_selector).encode("ascii"),
domain="robogyan.tech".encode("ascii"),
privkey=dkim_private.encode("ascii"),
include_headers=headers,)
msg["DKIM-Signature"] = sig.decode("ascii").lstrip("DKIM-Signature: ")
The raw output did reflect the signature with the above code but DKIM still failed.
There seems to be no problem with the authentication whatsoever since the server replies with "Authentication succeeded"
Edit:
DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed;
d=mydomain.tld; s=default; h=Subject:To:From:MIME-Version:Content-Type:
Sender:Reply-To:Date:Message-ID:Cc:Content-Transfer-Encoding:Content-ID:
Content-Description:Resent-Date:Resent-From:Resent-Sender:Resent-To:Resent-Cc
:Resent-Message-ID:In-Reply-To:References:List-Id:List-Help:List-Unsubscribe:
List-Subscribe:List-Post:List-Owner:List-Archive;
bh=giCDGo/0duFr1Ex65l7Ixc3N45EAULK+gw5cHV8pO0k=; b=DR08Q+CjgOLqo8WkLJs/XROfTw
Z7+ph+qnzi5p49cT3+UwQolcL1CKIVPk7XRkL8WZ3FFa9hZuc6TumquRSiYd5uR0AC5Z3lopEfnQe
fdbOOTRnks2ZzoOnQusy/gmydUttypu8wTthFhy7vTWXMFcdI29X/HkrokCtiGKCoD2u2kWBtn2sm
3/aP83lBbMpcWsNbvo3HTsL71o8QPd6bVKpqRGyAy89cAwMLwP4dnJ9WcCxxNzowlJNPQja3o5W16
t3rG/KizcRehjaDUXhPPRF/4RdYUSIi/SGNwmIPwvkZNc17k3wQpszKeG6/Ujgax/i7Li7V7dLJBT
Fu/x6xDA==;
Signed-by: myemail#mydomain.tld
Expected-Body-Hash: giCDGo/0duFr1Ex65l7Ixc3N45EAULK+gw5cHV8pO0k=
Here's the DKIM of the failing email if that helps. The expected body hash and the received body hash match too. I am not sure what the problem is then.
After a lot of research and brute force approaches, I finally found the solution to my problem.
I needed to include the Message-ID and the date in the headers as well.
Adding the following lines to the code helped me pass the verification.
msg['Date'] = email.utils.formatdate()
msg['Message-ID'] = email.utils.make_msgid(domain='mydomain.tld')
Important note: you need to add your smtp client's machine IP address to InternalHosts list, because OpenDKIM will check client's permission with these rules.
The you need to add this line to your /etc/opendkim.conf:
InternalHosts file:/etc/opendkim/TrustedHosts # or any location you want
Content of /etc/opendkim/TrustedHosts could look like:
127.0.0.1
::1
localhost
<server_ip>
hostname.example1.com
example1.com
hostname.example2.com
example2.com
...
It's just for example. You need to put here your python smtplib-client machine's address (ip/host).
Then just restart your opendkim:
$ sudo service opendkim restart
I am trying to send messages to my phone using the SMTP protocol. If I log into my Google Account (for which I've enabled less secure apps) I'm able to send a message to '5551234567#tmomail.net'. The subject and body of the email arrive on my phone as a text message.
However, when I try to do the same with Python's smtplib library, I don't get a message. Here's the code I'm using:
import smtplib
# Establish a secure session with gmail's outgoing SMTP server using your gmail account
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
# the account that will send the emails
server.login('me#gmail.com', 'password')
# sendmail(from, to, msg)
server.sendmail('me#gmail.com', '5551234567#tmomail.net', 'hey there!')
Does anyone know what I can do to get the text message to come through from the smtplib? Any suggestions are very welcome!
Try to check the link below.
If seems like you for forgot
server.ehlo()
How to send an email with Gmail as provider using Python?
Please let us know if you see python message in SENT emails folder of Gmail Inbox.
If yes, try to find a differences between one you sent from browser and one you sent from python API.
I'm making a script that notifies people about some pending tickets in JIRA. These notifications are sent by e-mail, I already got the notification to trigger, but I'm having problems sending the emails.
I can send them using gmail but when I tried to do it with my official account (the one that the company gave me) I am not able to send them. IT guys already provided me the 'localhost' because they use SMTP relays and the port, but they keep telling me that I should start SMTP without authentication, I'm not very sure of how to do this.
The example I found on internet was this:
import smtplib
fromaddr = 'Axel.Sa#mydomain.com'
toaddrs = ['Axel.Sa#mydomain.com']
msg = '''
From: {fromaddr}
To: {toaddr}
Subject: testin'
This is a test
.
'''
msg = msg.format(fromaddr=fromaddr, toaddr=toaddrs[0])
server = smtplib.SMTP('localhost:25')
server.starttls()
server.ehlo("mydomain.com")
server.mail(fromaddr)
server.rcpt(toaddrs[0])
server.data(msg)
server.quit()
But I keep getting this error, If someone can tell me the proper way of sending emails by SMTP without authentication I will be very grateful.
Check this stack:
How to send an email without login to server in Python
change your smtplib.SMTP('localhost:25') to smtplib.SMTP('localhost', 25)
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 = 'realmail#gmail.com'
fromshow = 'fakemail#gmail.com'
toaddy = ['rec01#gmail.com', 'rec02#gmail.com']
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()
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.
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.
I want to know why this code can't send email.
import smtplib
content = 'test'
mail = smtplib.SMTP('smtp.gmail.com',587)
mail.ehlo()
mail.starttls()
mail.login('surapon#gmail.com','222222')
mail.sendmail('surapon#gmail.com','youremail#gmail.com',content)
mail.quit
It shows:
SMTPAuthenticationError: (535, '5.7.8 Username and Password not accepted. Learn more at\n5.7.8 support.google.com/mail/answer/14257 ho10sm6301275pbc.27 - gsmtp')
Later, it shows:
SMTPAuthenticationError: (534, '5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbu87\n5.7.14 wdTx8uq_F_WXKXEVia5I3DTMdhzuJL967nviDbOqgBU9lHzjzIHX69az6PFAzff6lA2uGJ\n5.7.14 qCqwJzys1OcoqMzMNUx5o5ja_a3XHatcxE-jqsHjqWCwYR1WVUEmBfGvUIBzgm7iUyGOXq\n5.7.14 RdYOqEx5GLAe05yUhGq-z-JphFKH-x-aA0TwEc-hyEnecghY1ZLtMMsowPhFGa1XGPnNO3\n5.7.14 8XE4yhQctKtYySbTSiQqBUmmV4qE> Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 support.google.com/mail/answer/78754 eu5sm6412101pac.37 - gsmtp')
I created yagmail as a package to make it really simple to send emails.
Please try the following:
import yagmail
yag = yagmail.SMTP('surapon#gmail.com', 'password')
yag.send('youremail#gmail.com', subject = 'hi', contents = content)
There are some useful other tricks you can do with the package, such as never having to enter the password again (while still being secure), and it makes it extremely easy to send attachments.
Install with either
pip install yagmail # python 2
pip3 install yagmail # python 3
and for more information please have a look at github.
Due to security issues gmail blocks accessing mail via code or program
But still you can use gmail to send mail via code if you do the following things
What i have done in code :
1.Added a error object to get the error message
import smtplib
try:
content = 'test'
mail = smtplib.SMTP('smtp.gmail.com',587)
mail.ehlo()
mail.starttls()
mail.login('surapon#gmail.com','222222')
mail.sendmail('surapon#gmail.com','youremail#gmail.com',content)
mail.quit
print "Successfully sent email"
except smtplib.SMTPException,error:
print str(error)
print "Error: unable to send email"
If u ran this code u would see a error message like this stating that google is not allowing u to login via code
Things to change in gmail:
1.Login to gmail
2.Go to this link https://www.google.com/settings/security/lesssecureapps
3.Click enable then retry the code
Hopes it help :)
But there are security threats if u enable it
This is because google considers python SMTPLIB less secure. The link in the error message leads you to the answer.
Within that link there is another link to allowing "less secure" apps to send mail.
https://support.google.com/accounts/answer/6010255
This allows you to specifically allow your application to send email. They provide very little information on what constitutes the security issue.
The link they provide to give explicit access is
http://www.google.com/settings/security/lesssecureapps within the earlier link.
I'll explain what you're trying to do. You're attempting to do an SMTP with the following credentials:'smtp.gmail.com',587
Then you're attempting to login with your gmail creds. Totally wrong.
What you want to do is:
import smtplib
content = 'test'
me = 'surapon#gmail.com'
you = ['someOther#gmail.com']
mail = smtplib.SMTP('localhost')
msg['Subject'] = 'Hello'
msg['From'] = me
msg['To'] = you[0]
#mail.ehlo()
#mail.starttls()
#mail.login('surapon#gmail.com','222222')
mail.sendmail(me, you, msg.as_string())
mail.quit()
Do not include the #gmail.com in your credentials. I used your code with my username (without #gmail.com) and password and was able to send a message.
import smtplib
content = 'test'
mail = smtplib.SMTP('smtp.gmail.com',587)
mail.ehlo()
mail.starttls()
mail.login('surapon','222222')
mail.sendmail('surapon#gmail.com','youremail#gmail.com',content)
mail.quit