Send emails through gmail using flask-mail - python-3.x

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

Related

Is there a way to send appengine mail with nodejs without use an intermediary service like sendGrid or mailJet

I am a Python developer, but the circumstances of a project I am working on now, oblige me to find a solution in Node.js
This is the easy python code to send mail but, is there a google app engine way like this in nodejs without use an intermediary service like mailJet or sendGrid?
def send(recipient, sender, subject, body):
isHTML=True
print("recep: "+recipient)
logging.debug(u'Sending mail {} to {}'.format(subject,
unicode(recipient)).encode(u'utf-8'))
message = mail.EmailMessage(
sender=sender,
subject=subject,
to=recipient
)
if isHTML:
message.html = body
else:
message.body = body
message.check_initialized()
message.send()
Thank's for your understanding and help.
The simple example you posted uses the app engine specific Mail API, available only in the first generation standard environment (python 2.7, java 8, php 5.5 and go 1.9 - see the tabs in the referenced documentation page).
Node.js support was added only in the second generation standard environment, which has no such API available.

Is there a way to send the verification email with the Firebase Admin SDK from my Node.js server?

Is there a way to send the email verification email from my server ?
This is how it's done on the client:
authData.sendEmailVerification().then(function() {
Is there a way to do it on the server ?
firebaser here
To my surprise there currently is no option to send verification email from within the Admin SDK. I'd recommend you file a feature request.
What you can do from the Admin SDK is update a user profile to mark their email as verified. This allows you to take control of the entire verification flow if you want to, finishing with a call to admin.auth().updateUser(...) (on Node.js, see the link for other supported languages).
I just came across the same problem as you. There is a function to generate the verification link using user's email address.
I used this function on an array of email addresses, then load the result to my mail automation API to send mails out. This function is weirdly not documented:
admin.auth().generateEmailVerificationLink([EMAIL_ADDRESS])
You can use :
axios.post('https://identitytoolkit.googleapis.com/v1/accounts:sendOobCode?key=[API_KEY]',
{ requestType: 'VERIFY_EMAIL', idToken: response.data.idToken }
)
https://firebase.google.com/docs/reference/rest/auth#section-send-email-verification

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.

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.

Web2py - Using a Gmail address

I am beginner with web2py. I have just created a new project.
I want to use a gmail address, let's say g#gmail.com. What do I need to modify ?
mail.settings.server = 'logging' or 'smtp.gmail.com:587' # your SMTP server
mail.settings.sender = 'g#gmail.com' # your email
mail.settings.login = 'g#gmail.com:mypassword' # your credentials or None
Is this OK ?
What is the purpose of 'logging' ?
Should be
mail.settings.server = 'smtp.gmail.com:587'
Setting mail.settings.server = 'logging' has the effects of logging to console requests for sending emails but does not send the emails. It is useful for debugging email problems.

Resources