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
Related
I have created python file that can send email using less secure apps turned on, but I need it off. How can I send email with 2FA?
# import simple mail transfer protocol library
import smtplib
# import EmailMessage method
from email.message import EmailMessage
contacts = ['<email#email.com>', '<email2#email.com>']
EMAIL_ADDRESS = '<my_gmail>'
EMAIL_PASSWORD = '<my_gmail_password>'
# Create empty Email Message object
msg = EmailMessage()
msg['Subject'] = 'Automated python email sender 5'
msg['From'] = EMAIL_ADDRESS
msg['To'] = contacts
msg.set_content('<sample_content>')
# contact manager we will make sure our connection is closed automatically without us doing it manually
# 465 is the port number for plain SMTP_SSL
# SMTP_SSL means you do not have to use ehlo() ans starttls()
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
smtp.send_message(msg)
What should I add to make 2FA work?
I believe you would need to set up an App passwords let you sign in to your Google Account from apps on devices that don't support 2-Step Verification. Learn more
Its basically something thats setup in the users Google account.
Another thing to look at would be Display captcha
if that doesn't work you might need to look into Xoauth2
if you require 2fa
If you want to support 2fa then you should not be using the SMTP server and should be going though the Gmail API and using Oauth2 which will prompt a user to connect via their google account and google will control the 2fa themselves. SMTP servers are not designed to handel 2fa
Try setting up App Password for your Gmail. and used that app password for smtp login.
This will help Set Up APP-Password
Under security you have to generate a password for your application:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('demo#gmail.com', 'password generated by google')
server.sendmail('demo#gmail.com', 'demo#icloud.com', 'Mail sent from program')
print('Mail Sent')
as you can see, you enter your email but instead of typing your own password you enter the password generated by google for your application
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 trying to send an email from a Google account using Python's smtplib, but getting an error, and now I'm kind of at a loss. Google responds with the following: Please log in via your web browser and then try again. Learn more at https://support.google.com/mail/answer/78754.
The account has two factor authentication enabled, so I'm using an app specific password for my login. To my understanding, this should then work without enabling the setting for less secure apps, shouldn't it? I've been doing the same with another account while testing without a problem, but now I finally got the credentials for the proper account and there it won't accept the authentication.
I'm aware that there is a Python Gmail API thingy to use with OAuth, but if at all possible I don't want to include more packages and rewrite much, and I don't really want to enable the "less secure apps" setting either.
Is there a way to get this working without either?
If it makes a difference, here is the code I use for sending email. As said before, this was working fine with another account, so I'm not sure if it's actually relevant.
def send_mail(to_address, subject, body):
smtp_user = "myaccount#domain.com"
smtp_password = "MyAppPasswordFromGoogle"
server = "smtp.gmail.com"
port = 587
msg = MIMEMultipart("alternative")
msg["Subject"] = subject
msg["From"] = smtp_user
msg["To"] = to_address
msg.attach(MIMEText(body, "html"))
s = smtplib.SMTP(server, port)
s.connect(server, port)
s.ehlo()
s.starttls()
s.ehlo()
s.login(smtp_user, smtp_password)
s.sendmail(smtp_user, to_address, msg.as_string())
s.quit()
Edit:
There is an interesting difference between the two accounts: on https://myaccount.google.com/lesssecureapps, my old (working) one says "this setting isn't available for accounts that have two factor authentication enabled", while the new one says "this setting is managed by your domain administrator", even though both use 2FA and it's also forced in both domains. So I suppose there is some setting that the domain admin has to change, but I don't know which one that would be.
I tried to replicate exactly your case (with an account that has a two factor authentication enabled). After creating my app password, I used it in the code.
Anyway, I think your problem is the following:
s = smtplib.SMTP(server, port)
s.connect(server, port)
You execute the connection twice.
Try with
s = smtplib.SMTP()
s.connect(server, port)
or just this
s = smtplib.SMTP(server, port)
The entire code:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
smtp_user = 'myUser#gmail.com'
smtp_password = 'my16charactersAppPassword'
server = 'smtp.gmail.com'
port = 587
msg = MIMEMultipart("alternative")
msg["Subject"] = 'Why,Oh why!'
msg["From"] = smtp_user
msg["To"] = "destinationUser#gmail.com"
msg.attach(MIMEText('\nsent via python', 'plain'))
s = smtplib.SMTP(server, port)
s.ehlo()
s.starttls()
s.login(smtp_user, smtp_password)
s.sendmail(smtp_user, "destinationUser#gmail.com", msg.as_string())
s.quit()
As of now, google will remove the "Allow unsecure apps options" as suggested by other answers till May 30, 2022. Now you would need to generate specific app passwords.
Go to Google Accounts Page
Turn on the 2-step verification.
Security > App passwords
Select "Other apps" from the app menu.
This gives you app password. You could use the same email and this password to login with your python script
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.