Python SMTP Authentication error when sending email through Outlook only when password is provided - python-3.x

I am trying to use the generic python SMTP lib modules for sending an email from an outlook web application (not office 365) through Python. I am using the right host server name and port no. But still, I am unsure why I am receiving an authentication error. I understand that this is a frequently asked question, but I still wonder why it is unable to authenticate. Any help on this would be appreciated. Thank you.
Our email is configured with a DUO set-up (Two-factor authentication). I initially assumed this might be the reason. But the other methods I used worked perfectly fine without doing any additional setups
Some methods I tried were.
Using Python's win32com.client module in Python for sending email
through Desktop Outlook App.
Using Powershell to send an email
The code is pretty straight forward and simple.
import smtplib
from getpass import getpass
email = '********'
password =getpass("Enter your password")
with smtplib.SMTP('xxxx.xxx.xxx',25) as smtp:
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login(email,password)
subject = 'Test'
body = 'Testing email'
msg = f'Subject:{subject}\n\n{body}'
smtp.sendmail(email,email,msg)
It always shows this error, irrespective of the ports I am using.
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (535, b'5.7.8 Error: authentication failed: authentication failure')
EDIT:
Ok!! so the code absolutely runs fine if I remove the login and prompt password statement. But this seems to be dangerous and I am not sure why it's allowing us to send emails even though we are not logged in. Maybe the Windows Server Active Directory is already registered on the domain

Related

Send emails through gmail using flask-mail

I have a simple CRUD webapp set up in Python/Flask, when one particular function is activated (approving a request) I'd like to send an email notification to the user, but for all I've tried I can't get the email to send through my code.
Here is my config file with all the relevant environment variables set (inside of a Config object):
MAIL_SERVER = 'smtp.gmail.com'
MAIL_PORT=465
MAIL_USE_SSL=True
MAIL_USERNAME = '**#gmail.com'
MAIL_PASSWORD = '**'
I have also tried calling app.config.update(those values) in my app/init.py file. Here is the current code to do so
mail = Mail()
def create_app(config_name):
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(app_config[config_name])
app.config.from_pyfile('./config.py')
app.config.update(
MAIL_SERVER='smtp.gmail.com',
MAIL_PORT=465,
MAIL_USE_SSL=True,
MAIL_USE_TLS=False,
MAIL_USERNAME = '**#gmail.com',
MAIL_PASSWORD = '**')
mail.init_app(app)
And finally here is the code where I actually attempt to send the email:
msg = Message(html=html, sender='**#gmail.com', subject='Your Reservation for %s' % reservation.item.name, recipients=['**'])
mail.send(msg)
Additionally, it currently fails silently and I don't know how to even view what error is happening. Any help is much appreciated!
My suggestion in the comments was indeed the answer to the question.
Enabling "Less Secure Apps" in the Google Account settings was the necessary step to fix the hangup the OP was experiencing. This link from Google's support page walks you through how to enable this option.
I think, you should switch your sending protocol to TLS
this is sample from my project
MAIL_SERVER='smtp.gmail.com',
MAIL_PORT=587,
MAIL_USE_TLS=True,
MAIL_USERNAME = '**#gmail.com',
MAIL_PASSWORD = '**'
for me this works very well.
Now that Google is removing the less-secure app access feature due to security reasons, the best way to get around this is to use Sendgrid. They provide 100 free emails per day forever. You can register your same Gmail address as a single sender in SendGrid. Generate an API key and use it in your flask app to send emails.
For reference: Sending Emails from Python Flask Applications With Twilio SendGrid

Spotipy - Cannot log in to authenticate (Authorization Code Flow)

I am working with the Spotipy Python library to connect to the Spotify web API. I want to get access to my Spotify's user account via Authorization Code Flow. I am using Python 3.5, Spotipy 2.4.4, Google Chrome 55.0.2883.95 (64-bit) and Mac OS Sierra 10.12.2
First, I went to the Spotify Developer website to register the program to get a Client ID, a Client Secret key and enter a redirect URI (https://www.google.com) on my white-list.
Second, I set the environment variables from terminal:
export SPOTIPY_CLIENT_ID='my_spotify_client_id'
export SPOTIPY_CLIENT_SECRET='my_spotify_client_secret'
export SPOTIPY_REDIRECT_URI='https://www.google.com'
Then I try to run the example code typing 'python3.5 script.py my_username' from terminal. Here is the script:
import sys
import spotipy
import spotipy.util as util
scope = 'user-library-read'
if len(sys.argv) > 1:
username = sys.argv[1]
else:
print "Usage: %s username" % (sys.argv[0],)
sys.exit()
token = util.prompt_for_user_token(username, scope)
if token:
sp = spotipy.Spotify(auth=token)
results = sp.current_user_saved_tracks()
for item in results['items']:
track = item['track']
print track['name'] + ' - ' + track['artists'][0]['name']
else:
print "Can't get token for", username
When running this code, it takes me to a log in screen on my browser. I enter my Spotify's credential to grant access to my app. But when I finally click on 'log in' (or 'Iniciar sesiĆ³n' in Spanish) nothing happens. I tried to log in with my Facebook account but it does not work either. It seems that I get a Bad Request every time that I click on 'log in'. Here is a capture of Chrome:
The process is incomplete because when trying to enter the redirect URI back on terminal I get another Bad Request:
raise SpotifyOauthError(response.reason)
spotipy.oauth2.SpotifyOauthError: Bad Request
I tried to restart my computer, clean my browser cookies, use another different browser but did not work. It seems that I am not the only one having this problem. Is it maybe a bug? Please, avoid answers like "read the documentation of the API going here". Thank you.
Solved it. In order to run the Authorization Code Flow example code provided in the Spotipy's documentation correctly, I specified the redirect URI in line 13 of the example script when calling util.prompt_for_user_token, even when I had done this previously when setting environment variables:
token = util.prompt_for_user_token(username, scope, redirect_uri = 'https://example.com/callback/')
Likewise, do not use https://www.google.com or similar web address as your redirect URI. Instead, try 'https://example.com/callback/' or 'http://localhost/' as suggested here. Do not forget that the redirected URL once you are logged in must have the word code included.
Cheers,

ec2 node.js server not sending email - any ideas?

I have a website that I'm getting back up after a year+ of being down. I haven't made any code changes, and I've got the site back up and everything is working as before except for the site/app sending email.
It's an ubuntu node.js server. It's hosted on Amazon and I had to create another instance and repoint the dns, etc. An example code snippet that used to work but now doesn't:
var emailServer = email.server.connect({user:"<my gmail>",password:"<mypw>",host:"smtp.gmail.com",ssl:true});
emailServer.send({
text: "Your username is: " + userName + ".",
to: emailAddress,
subject: "Activate Your a2zCribbage Account",
attachment: [...]
}, function(err, message) { if (err) console.log(err); });
When I first tried to send email the gmail account I use got a message "sign-in attempt prevented" Someone just tried to sign in to your Google Account <account> from an app that doesn't meet modern security standards.
I followed what Google said and changed the security to allow apps, but still nothing gets sent.
What am I missing? What other things can I try? Do ec2 severs not just allow email to be sent by default?
Gmail is not a platform for sending automated email. Just because you can doesn't mean it's designed for doing so.
AWS EC2 instances are also problematic for sending email; the ports may be blocked or throttled, you are certainly getting higher spam scores for doing so.
The canonical solution is to use AWS SES. Here's sample code and here's the documentation. There's also a simple third-party library.

Sending email using nodemailer doesn't works on internet service but on local server

I am trying to send email from my node.js app using nodemailer. I am successful in sending email from my local server after enabling less secure apps on google account.
But when I deployed my code to heroku, it is unable to send email because google is blocking my login attempts. So I logged in to my account and clicked on the option that the login attempt was from me indeed. However it still is not working. I then set up a project on runnable.com and got the same sign in prevented. I did the same for this and accepted it as my sign in attempt. However I am still not able to send emails.
The error that is coming is this :
Server listening on port 80
Failed in sending mail
{ success: false, existing: false, sendError: true }
{ [Error: Invalid login]
code: 'EAUTH',
response: '534-5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbsNg\n534-5.7.14 LiCfP8u0IX20V3Y1nFt7iYuwJCPg4LVgRxVvEPO5y4-XOjzSsm_xa0XIBE3NP2bM5euv4A\n534-5.7.14 m6LSg0_DQ
Qj9kOm_JuwykQxVyYSKaLGyeibhi_cHtx3Pu4I4UISJCPt3TvHdxCUebMzTbu\n534-5.7.14 2F9wLa-IFpKHf9HPap4Aeu11Nup9ZAlpOCGAmcnbERFeAufeIgAsExtGkrmV2X7mktJ5nq\n534-5.7.14 epNHDpwg2EwMVwzOrpt8rGZahYvs> Please log i
n via your web browser and\n534-5.7.14 then try again.\n534-5.7.14 Learn more at\n534 5.7.14 https://support.google.com/mail/bin/answer.py?answer=78754 a76sm5828252oig.11 - gsmtp',
responseCode: 534 }
Please Help. I am in desperate need of getting it running.
I have the same issue, grap the link on your respone message "https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbsNg\n534-5.7.14" and paste to browser, you will see an announcement that showing google just blocked your sign-in request by cause it perform from strange device, then you can follow google instruction to accept that device.
It's work in my case. But I don't know what happen if heroku dynos sleep then waked up again, maybe it change the machine and you would got this problem again.
In this case, considering using a vps for hosting your mailing app.

oauth2, imap, gmail - fetching mails - gmail api is down and can't find reference to oauth2

I have a requirement (flexible) to use oauth2. (existing architecture/code)
I have a need to do some text manipulation of subscriber's email headers.
Solutions I've tried.
I've tried to download the sample code for java and it correctly connects to gmail's imap servers. It however responds with oath_version=1 and is expecting a password. I've tried to massage the code to change the params as other api's like their Contacts api oauth2 without success.
Question:
(multipart)
Api is down:http://code.google.com/googleapps/domain/email_migration/developers_guide_java.html any reference online would be ideal (it has been down for at least half a week since last week Wed). If you wondered - yes I did post on their forums before asking here for the updated link.
Is there a way to: a) make oauth2 request and b) Any (minimal) code exaples I can look at would be great.
Thanks in advance for reading this post.
Here is a working, Ruby example of fetching email from Google using the OAuth2 protocol:
imap = Net::IMAP.new('imap.gmail.com', 993, usessl = true, certs = nil, verify = false)
imap.authenticate('XOAUTH2', 'example#gmail.com', 'oauth2_access_token_goes_here')
imap.select('INBOX')
imap.search(['ALL']).each do |message_id|
msg = imap.fetch(message_id,'RFC822')[0].attr['RFC822']
mail = Mail.read_from_string msg
puts mail.subject
puts mail.text_part.body.to_s
puts mail.html_part.body.to_s
end
Note: This example uses ruby mail gem and gmail_xoauth gem, so you will need those installed for this code sample to work. I am also using the omniauth and omniauth-google-oauth2 gems to handle logging the user in and using the access token.

Resources