Search This Blog

Sunday, June 28, 2020

Python Gmail BCC SMPT

I was lacking personal examples for a Python SMTP sender and ran into the puzzle of BCC without listing the recipients in the header. It started with a discussion of timeouts of governing connections against a default receive connector on a Microsoft Edge Transport server, so there's a sleep in there too.

It's not perfect, but it is a good starting place....

#!/usr/bin/python

#
# gmail maximum message recipients in 24 hours: 500
#

import smtplib, getpass, time, sys

def Send_BCC_gmail(username, password, bcc):
    message_subject = "bcc only test"
    message_text = "this is \r\nonly \r\na test"

    flServerConnect = False
    try:
        SMTPServer = smtplib.SMTP_SSL('smtp.gmail.com', 465)
        SMTPServer.set_debuglevel(1)
        SMTPServer.login(username,password)
        flServerConnect = True
    except:
        e = sys.exc_info()[0]
        print("Error: %s" % e)

    if flServerConnect == True:
        try:
            for toaddr in bcc:
                message = "From: %s\r\n" % username \
                    + "To: %s\r\n" % toaddr \
                    + "Subject: %s\r\n" % message_subject \
                    + "\r\n" \
                    + message_text
                SMTPServer.sendmail(username, toaddr, message)
                time.sleep(.002)
        except:
            print("Error: %s" % sys.exc_info()[0])
            print("Error: %s" % sys.exc_info()[1])
            print("Error: %s" % sys.exc_info()[2].tb_lineno)
            print ('\r\nNot sent...   : (\r\n')
        finally:
            SMTPServer.quit()
            print ('Sent...   : )')

       
       
def main():
    username = input("Type your username and press enter: ")
    password = getpass.getpass("Type your password and press enter: ")
    bcc=[]
    bccpart = "."
    while bccpart > "" :
        bccpart = input("Additional Name. end list with an empty line by itself: ")
        if bccpart > "":
            bcc.append(bccpart)
    print(bcc)
    ## bcc = ['lesleyphillipsii@yahoo.com','lesleyphillipsii@gmail.com']
    Send_BCC_gmail(username, password, bcc)

if __name__ == "__main__": main()






When you run it it produces the following output...



And here is the important part of the header...