Search code examples
pythonpython-2.7emailgmailsmtplib

Python Can't Send Emails to Gmail


I have a python script to send emails. I utilize this to send alerts to my email and phone. But for some reason the emails are not received when sending to a gmail account. The big difference that I see between my code and other examples is I cannot use the smtp.gmail.com. Here's my email/text function:

import smtplib

sender = '[email protected]'
smtpObj = smtplib.SMTP('smtp.company.com')

def text_func ( subject,text_message ):
    text_receivers = ['##########@vtext.com',
        '[email protected]',
        '[email protected]'
    ]
    text_message = """Subject: %s

    %s
    """ % (subject, text_message)

    smtpObj.sendmail(sender, text_receivers, text_message)

The above code works for sending an sms to my phone and my work email but not to gmail. I checked and made sure the email doesn't show up in a spam folder. Google seems to be blocking it completely. Any ideas?


Solution

  • Found the solution.

    import smtplib
    from email.mime.text import MIMEText
    
    sender = '[email protected]'
    smtpObj = smtplib.SMTP('smtp.company.com')
    
    def text_func ( subject,text_message ):
        text_receivers = ['##########@vtext.com',
            '[email protected]',
            '[email protected]'
        ]
    
        cont = '''\
           <html>
             <head></head>
             <body>
               <p>{0}</p>
             </body>
           </html>
           '''.format(text_message)
    
        msgTo = ""
        for person in text_receivers:
            msgTo += "{0} ".format(person)
    
        msg = MIMEText(cont, 'html')
    
        msg['Subject'] = subject
        msg['From'] = sender
        msg['To'] = msgTo
    
        smtpObj.sendmail(sender, text_receivers, msg.as_string())