Search code examples
pythonemailgmailsmtplib

Google SMTP less secure applications


I am trying to send email via Google SMTP server using the following simple python and mailclient.

I am a bit confused about the part where Google flags this script as insecure and requires me to allow less secure applications to access the sender's gmail account.

Is there any way to solve this problem without having to allow less secure applications to access my gmail account.

#Make necessary imports

import mailclient

#Craft the message
msg = mailclient.Message("This will be the subject", "This will be the body content", '[email protected]', '[email protected]')

#Create server object with gmail

s = mailclient.Server('smtp.gmail.com', '587', '[email protected]', 'senderpassword', True)

#Send email

s.send(msg)

Solution

  • Hard to say, because Google is not very explicit for what they call unsecure applications, but I guess that they are applications that use ports 25 or 587. On those ports, the connection is initially established on an unencrypted channel, and becomes encrypted only when (and if) the STARTTLS command is issued.

    So I guess that you should try to establish a connection directly over SSL on port 465. I do not know whether it is possible using mailclient but with the standard library modules, it should be as simple as:

    import smtplib
    from email.message import EmailMessage
    
    msg = EmailMessage()
    msg['Subject'] = "This will be the subject"
    msg['From'] = '[email protected]'
    msg['To'] = [ '[email protected]' ]
    msg.set_content("This will be the body content")
    
    server = smtplib.SMTP_SSL('smtp.gmail.com')
    server.login('[email protected]', 'senderpassword')
    server.send_message(msg)
    server.quit()