I'm trying send email with a PDF attached. I have defined the next function:
def mail(to, subject, text, attach):
gmail_user = "email@gmail.com"
gmail_name = "name <email@gmail.com>"
gmail_pwd = "password"
msg = MIMEMultipart()
msg['From'] = gmail_name
msg['To'] = to
msg['Subject'] = subject
msg.attach(MIMEText(text))
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="%s"' % os.path.basename(attach))
msg.attach(part)
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_name, to, msg.as_string())
mailServer.close()
The problem is that the console shows the following error
smtplib.SMTPServerDisconnected: Server not connected
However, if I simply replace 'msg.as_string' with "Whatever string" it works fine. So I think that this issue happens when I try attach a PDF file.
Could you help me please ?
Thanks