Python电子邮件通知未发送

时间:2019-04-14 03:02:50

标签: python python-3.x function smtp

该代码应该将电子邮件发送到指定的地址,当我对“ TEXT”和“ SUBJECT”进行硬编码时,似乎可以正常发送,但是当我将其创建为函数并调用它时,它永远不会发送电子邮件,从不打印“已发送通知”消息。我想念什么?

尝试对TEXT和SUBJECT进行硬编码,它发送正常!注意:使用GMAIL时必须启用较少安全的应用程序!

import smtplib

class email_thing:

    def email_notification(self,SUBJECT,TEXT):

        TO = 'email@example.com'
        self.SUBJECT = SUBJECT
        self.TEXT = TEXT
        gmail_sender = 'email@example.com'
        gmail_passwd = 'examplepassword'
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.ehlo()
        server.starttls()
        server.login(gmail_sender, gmail_passwd)

        return self.SUBJECT
        return self.TEXT

        BODY = '\r\n'.join(['To: %s' % TO,
                            'From: %s' % gmail_sender,
                            'Subject: %s' % SUBJECT,
                            '',TEXT])
        try:
            server.sendmail(gmail_sender, [TO], BODY)
            print ('Notification Sent!')
        except:
           print ('error sending mail')

        server.quit()

test_send = email_thing()
test_send.email_notification(SUBJECT ='Test Email',TEXT = 'This is a test from python!')

1 个答案:

答案 0 :(得分:1)

删除

    return self.SUBJECT
    return self.TEXT

return立即退出方法,因此永远不会执行return之后的代码。