Search code examples
pythonsmtpgmailsmtplib

Email function does not work after put in a class


So basically I copy and pasted an email sending python script which works. This is the code:

import smtplib

gmail_user = 'email@email.com'
gmail_password = 'P@ssword!'

sent_from = gmail_user
to = ['bill@gmail.com']
subject = 'OMG Super Important Message'
body = 'Hey, whats up?\n\n- You'

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

%s
""" % (sent_from, ", ".join(to), subject, body)

try:
    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    server.ehlo()
    server.login(gmail_user, gmail_password)
    server.sendmail(sent_from, to, email_text)
    server.close()

    print ('Email sent!')
except:
    print ('Something went wrong...')

The result is as perfectly described: enter image description here

Unfortunately, I put the code within a class to execute as a function from another main function. Code is as below:

import smtplib

class EmailSending():
    def doneEmail(self):

        gmail_user = 'email@email.com'
        gmail_password = 'P@ssword!'

        sent_from = gmail_user
        to = ['bill@gmail.com']
        subject = 'OMG Super Important Message'
        body = 'Hey, whats up?\n\n- You'

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

        %s
        """ % (sent_from, ", ".join(to), subject, body)

        try:
            server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
            server.ehlo()
            server.login(gmail_user, gmail_password)
            server.sendmail(sent_from, to, email_text)
            server.close()

            print('Email sent!')
        except:
            print('Something went wrong...')

ef = EmailSending()
ef.doneEmail()

The only code that changed is that it is now in a class function. But when calling it, it returns a different result, shown below enter image description here

The email still sends to my email but everything else is out. Can anyone help me out? Thx


Solution

  • You have added spaces at the beginnings of the lines containing From: and so on. Remove them:

    class EmailSending():
        def doneEmail(self):
    
            gmail_user = 'email@email.com'
            gmail_password = 'P@ssword!'
    
            sent_from = gmail_user
            to = ['bill@gmail.com']
            subject = 'OMG Super Important Message'
            body = 'Hey, whats up?\n\n- You'
    
            email_text = """\
    From: %s
    To: %s
    Subject: %s
    
    %s
    """ % (sent_from, ", ".join(to), subject, body)
    
            try:
                server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
                server.ehlo()
                server.login(gmail_user, gmail_password)
                server.sendmail(sent_from, to, email_text)
                server.close()
    
                print('Email sent!')
            except:
                print('Something went wrong...')
    
    ef = EmailSending()
    ef.doneEmail()