Python send reply to a gmail error: AttributeError: ‘int’ object has no attribute ‘encode’

I have constructed the following code to reply to an existing email in my gmail account

msg = MIMEMultipart('') msg['From'] = sender msg['To'] = recipient msg['Subject'] = replySubj msg['In-Reply-To'] = uid msg.attach(MIMEText("I received your message"))  server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login(username, password) server.sendmail(sender, recipient, msg.as_string()) server.quit() 

I keep getting this error –> AttributeError: ‘int’ object has no attribute ‘encode’ which relates to this line

server.sendmail(sender, recipient, msg.as_string()) 

when I remove .as_string() I get this error: TypeError: expected string or bytes-like object