Sending email with python. Google disables less secure apps - python

I am trying to send email using python. My code was working fine before Google disabled 'less secure apps'. My email address and password are both correct.
server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
serverEmail = "EMAILADDRESS"
serverPw = "QWERTY"
server.login(serverEmail, serverPw)
subject = "Rejection"
body = "Hi! You've been unfortunately declined access to our system."
message = f'Subject: {subject}\n\n{body}'
server.sendmail("EMAILADDRESS", doctorEmail['email'], message)
server.quit()
I get this error now:
smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted.
I get this error when i use server.starttls():
smtplib.SMTPNotSupportedError: STARTTLS extension not supported by server.

2-step verification turn on then head over to App password
After is generated passwords
import smtplib
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as connection:
email_address = 'your_email_sender#gmail.com'
email_password = 'App_Passwords_is_generated'
connection.login(email_address, email_password )
connection.sendmail(from_addr=email_address, to_addrs='receiver_email#something.com',
msg="subject:hi \n\n this is my message")

This is working for me. You need to generate an app password for this. See https://support.google.com/accounts/answer/185833?hl=en
import smtplib as smtp
connection = smtp.SMTP_SSL('smtp.gmail.com', 465)
email_addr = 'my_email#gmail.com'
email_passwd = 'app_password_generated_in_Google_Account_Settings'
connection.login(email_addr, email_passwd)
connection.sendmail(from_addr=email_addr, to_addrs='recipient#something.com', msg="Sent from my IDE. Hehe")
connection.close()
For some reason, all of my emails are ending up in SPAM folder of the recipient account though.

Google disabled access for 'less secure apps' for a time on June 2, but around 7 PM US Eastern Time they re-enabled it. So if you just waited a few hours, you didn't have to do anything.
I suspect that somehow they got smacked with the 'law of unintended consequences' but it won't surprise me if they turn this access off again at some point.

Related

How to send mail from 10 minute disposable email via SMTP?

This is my code for the gmail smtp server.
def verify_email(self, user_email, sending_email, password):
port = 465
self.sending_mail = sending_email
self.password = password
if (re.fullmatch(regex, user_email)):
self.user_email = user_email
else:
raise Exception("Sorry, your email is invalid.")
self.email_msg = f"""
Subject: Verify Email
Is this you, {self.username}?
Please enter the code below to verify:
[{verify_code}]
From,
{self.sending_mail}
"""
context = ssl.create_default_context()
try:
with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server:
server.login(self.sending_mail, self.password)
server.sendmail(self.sending_mail, self.user_email, self.email_msg)
except:
print("An error has happened. Please check the spelling of your email, "
"or try again. 🙂")
How can I use the 10 minute mail SMTP server?
I used Google but I didn't understand any of it.
When I used Gmail I got this error:
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials g15-20020a056a0023cf00b004e17e11cb17sm9404507pfc.111 - gsmtp')
So I decided to use 10minute mail. In my gmail account, I can't change the settings to allow Less Secure Apps.
Gmail recently announced that they wouldn't allow unsecure connections like SMTP on May 30th of 2022.
Using SMTP through gmail requires that you enable the setting "Allow less secure apps" in account settings to be able to connect.
I'd try something like Yahoo, or Outlook, or another email provider that allows SMTP. Look up their server information, and what security privilege's you need to enable for the connection to happen for which provider you choose.
I'm not familiar with 10 Minute Mail, but just wanted to give that insight to Gmail's SMTP server. Hopefully someone else can help you set it up through 10 minute mail.

Send mail from Gmail smtp via python fail when authenticate [duplicate]

This question already has answers here:
How to send an email with Gmail as provider using Python?
(16 answers)
SMTPAuthenticationError 5.7.14 Please log\n5.7.14 in via your web browser
(10 answers)
Closed 7 years ago.
when i try to send mail using gmail and python error occurred this type of question are already in this site but doesn't help to me
gmail_user = "me#gmail.com"
gmail_pwd = "password"
TO = 'friend#gmail.com'
SUBJECT = "Testing sending using gmail"
TEXT = "Testing sending mail using gmail servers"
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(gmail_user, gmail_pwd)
BODY = '\r\n'.join(['To: %s' % TO,
'From: %s' % gmail_user,
'Subject: %s' % SUBJECT,
'', TEXT])
server.sendmail(gmail_user, [TO], BODY)
print ('email sent')
error:
server.login(gmail_user, gmail_pwd)
File "/usr/lib/python3.4/smtplib.py", line 639, in login
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (534, b'5.7.14
<https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbtl1\n5.7.14 Li2yir27TqbRfvc02CzPqZoCqope_OQbulDzFqL-msIfsxObCTQ7TpWnbxIoAaQoPuL9ge\n5.7.14 BUgbiOqhTEPqJfb02d_L6rrdduHSxv26s_Ztg_JYYavkrqgs85IT1xZYwtbWIRE8OIvQKf\n5.7.14 xxtT7ENlZTS0Xyqnc1u4_MOrBVW8pgyNyeEgKKnKNyxce76JrsdnE1JgSQzr3pr47bL-kC\n5.7.14 XifnWXg> 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 fl15sm17237099pdb.92 - gsmtp')
Your code looks correct. Try logging in through your browser and if you are able to access your account come back and try your code again.
Just make sure that you have typed your username and password correct
EDIT:
Google blocks sign-in attempts from apps which do not use modern security standards (mentioned on their support page). You can however, turn on/off this safety feature by going to the link below:
Go to this link and select Turn On
https://www.google.com/settings/security/lesssecureapps
Your code looks correct but sometimes google blocks an IP when you try to send a email from an unusual location. You can try to unblock it by visiting https://accounts.google.com/DisplayUnlockCaptcha from the IP and following the prompts.
Reference: https://support.google.com/accounts/answer/6009563
I have just sent an email with gmail through Python.
Try to use smtplib.SMTP_SSL to make the connection. Also, you may try to change the gmail domain and port.
So, you may get a chance with:
server = smtplib.SMTP_SSL('smtp.googlemail.com', 465)
server.login(gmail_user, password)
server.sendmail(gmail_user, TO, BODY)
As a plus, you could check the email builtin module. In this way, you can improve the readability of you your code and handle emails headers easily.

How to send authenticated email using Python?

I have a python function to send an email notification. I have included the login call to authenticate with my local SMTP server, however emails are being returned stating '553-mail rejected because your IP is in the PBL'. Further reading on https://www.spamhaus.org/pbl reveals that apparently I am not being prevented from sending email, I am simply required to authenticate first.
I have tried base64 encoding to avoid sending the password as plain text without success.
I have also looked at the Pysasl library, but I am a little unsure how I might use this for authenticating with my SMTP server.
Would anyone have any guidance as to the correct use of either base64 encoding, the pysasl library or if a better method exists for satisfying the correct authentication requirements?
My code is below.
def emailNotify(self,userid):
SMTPserver = 'localhost'
sender = '***' # blanked
username = '***' # blanked
receiver = '***' # blanked
pwd = '***' # blanked
text_subtype = 'plain'
msg = 'requested data was posted to dashboard for '+userid
subject = 'confirmation of POST\'d data for '+userid
try:
msg = MIMEText(msg, text_subtype)
msg['Subject'] = subject
msg['From'] = sender
conn = smtplib.SMTP(SMTPserver)
conn.login(username, pwd)
try:
conn.sendmail(sender, receiver, msg.as_string())
finally:
conn.quit()
except:
print('message sending failed')
Thanks in advance.
You have 2 ways of building a program for sending mail:
build a bullet proof solution:
analyze what server announces as its capabilities
choose the one that better meets your requirement
use that authentication method
actually send the mail
simply that means that you have to implement code for reading and decoding what the server returns (which can be weird) and also all various authentication methods, not speaking of TLS
use a custom connection method adapted to that server
read the documentation of the server to know what it declares to support
test it manually first through a mere telnet connection then in an interactive Python session (idle is enough here, but you can choose your prefered Python shell)
carefully program the way you have just tested - but leave relevant error messages in cases the server capabilities change...
IMHO much simpler...

Sending an email using Python

I'm trying to send myself an email using Python's smtplib module. Here's the code I'm trying to execute:
import smtplib
sender = 'manas.oid#gmail.com'
receivers = ['manas.oid#gmail.com']
message = """From: From Person <manas.oid#gmail.com>
To: To Person <manas.oid#gmail.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except smtplib.SMTPException:
print "Error: unable to send email"
However, I get a 'Error:unable to send email' message when I try to execute this script. What seems to be wrong with my script?
You did not login and you did not start the connection with smtpObj.starttls().
To add on to what #Malik says, below are the steps you need to perform before you'll be able to do anything with GMail (provided less secure apps can access your account, see below).
conn = SMTP('smtp.gmail.com',587)
conn.ehlo()
conn.starttls()
conn.ehlo()
conn.login(username,pwd)
conn.sendmail(username, emailID, message)
Note that after recent changes to GMail, you'll need to explicitly allow less secure apps to access your account. GMail would block your request to login until you enable it. Link to enable less secure apps to access: https://support.google.com/accounts/answer/6010255?hl=en
Gmail wouldn't let you send an unauthenticated email from an account.
Instead, use the Gmail API to send emails. Some useful links below:
Authentication: https://developers.google.com/gmail/api/auth/web-server
Email: https://developers.google.com/gmail/api/guides/sending

Sending an email via gmail through a python application

as indicated by the title I am having trouble sending an email via my gmail account through a python application.I have searched online for a solution but nothing seems to solve it and I thought I might ask here.
My code is the following:
FROMADDR = "myemail#gmail.com"
LOGIN = FROMADDR
PASSWORD = "mypass"
TOADDRS = "varis81#hotmail.com"
msg = "Test message"
server = smtplib.SMTP('smtp.gmail.com', 587)
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.login(LOGIN, PASSWORD)
server.sendmail(FROMADDR, TOADDRS, msg)
server.quit()
print "E-mail succesfully sent"
I get the message:
socket.error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
I tried different ports but it doesn't work also.I also tried hotmail but it causes the same problem.I am using Python 2.7 (don't ask :) ) on a Windows 7 machine developing on Eclipse using PyDev.
Any help would be great!
Thank you in advance.
I'm using the same construct on one of my servers. My code is below.
The only difference is the extra .ehlo() after '.starttls()`. This should not be the issue; from the RFC:
5.2 Result of the STARTTLS Command
The client SHOULD send an EHLO command as the first
command after a successful TLS negotiation.
According to the RFC, the server should not sever a connection if the client does not send ehlo after starttls, but Google could be more restrictive on their SMTP server. I'd check that first. (I've seen providers tighten down on these kinds of conditions to reduce spam, see Mailinator's 2007 writeup for instance.)
It could also be filtered ports - try running the code in the REPL and confirm which line is exceptioning, if it's the connect() you'll know it's network. If it's after, it's likely your usage of smtplib.
Of note, I also experienced occasional unclean shutdowns, resulting in the try/except around .close().
import smtplib
s = smtplib.SMTP()
s.connect("smtp.gmail.com")
s.ehlo()
s.starttls()
s.ehlo()
s.login("from#gmail.com", "frompass")
s.sendmail("fromname#gmail.com", toAddr, bytes)
try:
s.close()
except: pass
Well, since I cant post comments yet I'll have to attempt an answer..
Judging by this: Python SMTP Errno 10060
Perhaps a timeout would help?

Categories