Search code examples
pythonodoo

How to add a subject in sendmail()


//The below code is my python file. //I want to add a subject to this. while i'm adding subject parameter to sendmail(). //It shows error in odoo. //How could i do this!!!

Code:

 def sendotp(self):
          if self.mail:
                mail = self.mail
                otp = ''.join(str(random.randint(0,9))for i in range 
                server = smtplib.SMTP('smtp.gmail.com', 587)
                server.starttls()
                server.login(<mymail>,password)
                msg = 'Hi, your OTP is ,' +str(otp)
                server.sendmail('[email protected]',mail,msg)
                server.quit()
                      

Solution

  • You can send the smtp message using MIMEText parts

    import smtplib
    from email.mime.text import MIMEText
    
    def sendotp(self):
          if self.mail:
                mail = self.mail
                otp = ''.join(str(random.randint(0,9))for i in range 
                server = smtplib.SMTP('smtp.gmail.com', 587)
                server.starttls()
                server.login(<mymail>,password)
    
                # MIMEText mail message
                msg = MIMEText('Hi, your OTP is ,' + str(otp))
                msg['Subject'] = 'Test mail'
                msg['From'] = '[email protected]'
                msg['To'] = mail
    
                server.sendmail('[email protected]',mail,msg.as_string())
                server.quit()