How to send an email with Gmail as provider using Python?

后端 未结 14 1670
感情败类
感情败类 2020-11-22 03:29

I am trying to send email (Gmail) using python, but I am getting following error.

Traceback (most recent call last):  
File \"emailSend.py\", line 14, in <         


        
相关标签:
14条回答
  • 2020-11-22 03:56

    You down with OOP?

    #!/usr/bin/env python
    
    
    import smtplib
    
    class Gmail(object):
        def __init__(self, email, password):
            self.email = email
            self.password = password
            self.server = 'smtp.gmail.com'
            self.port = 587
            session = smtplib.SMTP(self.server, self.port)        
            session.ehlo()
            session.starttls()
            session.ehlo
            session.login(self.email, self.password)
            self.session = session
    
        def send_message(self, subject, body):
            ''' This must be removed '''
            headers = [
                "From: " + self.email,
                "Subject: " + subject,
                "To: " + self.email,
                "MIME-Version: 1.0",
               "Content-Type: text/html"]
            headers = "\r\n".join(headers)
            self.session.sendmail(
                self.email,
                self.email,
                headers + "\r\n\r\n" + body)
    
    
    gm = Gmail('Your Email', 'Password')
    
    gm.send_message('Subject', 'Message')
    
    0 讨论(0)
  • 2020-11-22 03:58

    Seems like problem of the old smtplib. In python2.7 everything works fine.

    Update: Yep, server.ehlo() also could help.

    0 讨论(0)
提交回复
热议问题