Python - Connect to Gmail and send mail - Error 534 InvalidSecondFactor - python

i want to include sending notifications mails through gmail in my python code.
I followed all the steps to do it:
import smtplib
Enable less secure app
Wait for 1 day
Set 2-verification access
Create 16 digits app password
Change my gmail password with the 16 digits app password
Log into my gmail account
Unlock Display Captcha
Run the code within 10 minutes
I still got the same error:
(534, b'5.7.9 Application-specific password required. Learn more at\n5.7.9 https://support.google.com/mail/?p=InvalidSecondFactor h25sm8001063qkg.87 - gsmtp')
This is my code:
import smtplib, ssl
port = 465 # For SSL or 465
smtp_server = "smtp.gmail.com"
sender_email = "my_mail#gmail.com" # Enter your address
receiver_email = "my_mail#gmail.com" # Enter receiver address
password = '16digtisapppass' # i've checked I can log in to my gmail account with it
message = """\
Subject: Hi there
This message is sent from Python."""
try:
server = smtplib.SMTP_SSL('smtp.gmail.com', port)
server.ehlo()
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
except Exception as e:
print(e)
# or
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
I've read these other posts:
https://stackabuse.com/how-to-send-emails-with-gmail-using-python/
http://stackoverflow.com/a/27515833/2684304
I'm not a professional coder, so maybe there is something simple that i'm missing.
I don't know what else could I do. Could anyone help me?

gmail port is 587
you are using AT&T port 465 just replace with 587port .

The problem is that the "2-Step Verification" is on your account.
Solutions:
Turn off 2-Step Verification and use your normal password account in your app (see this link for more details)
Sign in with App Passwords, An App Password is a 16-digit passcode that gives a less secure app or device permission to access your Google Account. App Passwords can only be used with accounts that have 2-Step Verification turned on (see this link or link2).

Related

Can't send emails on cpanel but I can when I host my code on my local computer

I am making a flask app with python. When I run the website on my local computer, my #app.route("/sendEmail") works. However, when I uploaded that same code to cpanel, that same route doesn't work on the actual website. Do i have to configure something in the cpanel settings to be able to send emails? I included the code below (assume flask app has been intitialized and all necessary libraries - I'm using smtplib and ssl - have been imported.
#app.route("/sendEmail") # DOESNT WORK ON ACTUAL WEBSITE
def send_email():
port = 465
smtp_server = "smtp.gmail.com"
sender = "sender#gmail.com" #not real value
receiver = "receiver#gmail.com" # not real value
password = "password"
message = f"""\
Subject: Email Verification Link
Please do not reply to this message.
Here is your verification link:
"""
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender, password)
server.sendmail(sender, receiver, message)
return redirect("verify")

Python Script for sending mail returns no errors but mail not received

Using my gmail account as a test for sending mail using python. It appears the mail is getting sent (or at least passes over the mail server) but it is not being received. I cannot seem to find any logs that would allow me to trace the email (Using Linux Mint 20). First question is where can I find these logs? Secondly, does anything in this script seem incorrect? Please assume that the data is correctly populated. My gmail account is set to allow less secure apps as well.
with open("config.json",) as config:
data = json.load(config)
smtp_server = data["MAIL"]["SMTP_SERVER"]
port = data["MAIL"]["SMTP_PORT"]
sender_email = data["MAIL"]["SMTP_ACCOUNT"]
password = data["MAIL"]["SMTP_PASSWORD"]
context = ssl.create_default_context()
try:
server = smtplib.SMTP(smtp_server,port)
server.ehlo()
server.starttls(context=context)
server.ehlo()
server.login(sender_email,password)
return server
except Exception as e:
print(e)
return None

smtplib.SMTPAuthenticationError: (535, b'5.7.3 Authentication unsuccessful

\I'm getting an authentication error. I'm 100% certain my email and password are correct (types them in). I've attached a picture of my office.outlook.com settings for IMAP and POPenter image description here
import smtplib
# initialize connection to our email server, we will use Outlook here
smtp = smtplib.SMTP('smtp.office365.com', port='587')
smtp.ehlo() # send the extended hello to our server
smtp.starttls() # tell server we want to communicate with TLS encryption
smtp.login('support#name.com', 'emailpassword') # login to our email server
# send our email message 'msg' to our boss
smtp.sendmail('support#name.com',
'support#name.com',
msg.as_string())
smtp.quit() # finally, don't forget to close the connection

Send email ( python smtp ) to a specific domain (not .Gmail)

import smtplib
from smtplib import SMTP
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
msg = MIMEMultipart()
msg['From'] = 'example1#gmail.com'
#Sender
msg['To'] = 'example2#uc.cl'
#Receiver
msg['Subject'] = 'python'
message = ' Wena mimo, como estai mimo'
msg.attach(MIMEText(message))
mailserver = smtplib.SMTP('smtp.gmail.com',587)
# identify ourselves to smtp gmail client
mailserver.ehlo()
# secure our email with tls encryption
mailserver.starttls()
# re-identify ourselves as an encrypted connection
mailserver.ehlo()
mailserver.login('example1#gmail.com', 'password')
#login to the account
mailserver.sendmail('example1#gmail.com','example2#uc.cl',msg.as_string())
mailserver.quit()
#I make a code that sends emails to differents mail(example #gmail and
#corporative ) but i try to send mail to XXXXXXXX#uc.cl (https://www.uc.cl) but this mail dont receive the message
This is a code for Python3 in Ubuntu 18.04 I dont know if the problem is the port:587 or the domain uc.cl or the code, maybe the domain uc.cl takes a high level on this security
THis domain its from a University
I assume the school mail server might try to block the mail coming from your python server.
A few things you could try...
Sending the email while connected to the school wifi. Maybe they don't block internal traffic
Try sending to a email server you set up just to check your code is working right
Make a new email account yahoo, etc and login with the code above and try sending to the other accounts you can test with. This should give you a good idea what is occuring.

python smtp gmail authentication error (sending email through gmail smtp server)

I have the following code
import smtplib
from email.mime.text import MIMEText
smtpserver = 'smtp.gmail.com'
AUTHREQUIRED = 1 # if you need to use SMTP AUTH set to 1
smtpuser = 'admin#myhost.com' # for SMTP AUTH, set SMTP username here
smtppass = '123456' # for SMTP AUTH, set SMTP password here
RECIPIENTS = ['online8#gmail.com']
SENDER = 'admin#myhost.com'
msg = MIMEText('dsdsdsdsds\n')
msg['Subject'] = 'The contents of iii'
msg['From'] = 'admin#myhost.com'
msg['To'] = ''online8#gmail.com''
mailServer = smtplib.SMTP('smtp.gmail.com',587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(smtpuser, smtppass)
mailServer.sendmail(smtpuser,RECIPIENTS,msg.as_string())
mailServer.close()
this code works fine on my desktop. but it failed with this error
smtplib.SMTPAuthenticationError: (535, '5.7.1 Username and Password not accepted. Learn more at\n5.7.1 http://mail.google.com/support/bin/answer.py?answer=14257 21sm4713429agd.11')
on my linux server.
Not sure what went wrong, should i open some port on my linux server?
Port 587 obviously needs to be open, but it probably is (or you wouldn't have gotten the detailed error msg in question). Python 2.5 vs 2.6 should make no difference. I think the issue has to do with "solving a captcha" once on the computer for which logins are currently getting rejected; follow the detailed instructions at the URL in the error message, i.e., http://mail.google.com/support/bin/answer.py?answer=14257
import random,time
for i in range(1,100):
y=random.randint(30,300)
time.sleep(y)
print ("Mailing for fun, Mail No: " + str(i))
msg = MIMEText('Testing mailing \n Mail No:' + str(i))
msg['Subject'] = 'Mail Number: ' + str(i)
Randomizing the mail interval to check smtp behavior :)
With a bit addition n modification, I got this to work to check our intermittent mail bouncing.

Categories

Resources