Search code examples
pythonsmtpgmail

Send email at specific time with millisecond precision


I would like to send email at given time preferably using gmail. The rationale behind this is that the school I am applying is ordering candidates based on when they receive the participation email after given time.

I could use gmail schedule send feature but there is X delay between sending email from gmail server to school email and it potentially should be achieveable to cut it down slightly so I thought about python script to do it. I think I can get around sending it at a given time but struggle to actually send the message.

There are threads in stackoverflow suggesting python solution e.g.: How do I schedule an email to send at a certain time using cron and smtp, in python? but unfortunately it looks like gmail disabled the option to send mails from non-authorized apps. Other threads suggest that enabling less secure apps is needed. Unfortunately, this setting has been closed by Google. What could be the way around it?

My sample code:

`

def send_mail():

    try:
        server_ssl = smtplib.SMTP_SSL('smtp.gmail.com', 465)
        server_ssl.ehlo()   # optional
        print('Server initialized')
    
    
        sent_from = gmail_user
        to = ['xxxxxxxx@gmail.com']
        subject = 'my subject'
        body = 'my body'

        email_text = """\
From: %s
To: %s
Subject: %s

%s
""" % (sent_from, ", ".join(to), subject, body)
        server_ssl.sendmail(sent_from, to, email_text)
        server_ssl.close()
    except Exception as inst:
        print('Something went wrong')
        print(type(inst))    # the exception instance
        print(inst.args)     # arguments stored in .args
        print(inst)

`

is returning an error:

<class 'smtplib.SMTPSenderRefused'> (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError


Solution

  • You need to supply the login to the account, as well as an apps password. You cant just send an email without being authenticated to the mail server.

    with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context) as server:
        print( 'waiting to login...')
        server.login(sender_email, password)
        print( 'waiting to send...')
        server.sendmail(sender_email, receiver_email, text)