0
votes

Getting "LazyImporter' object is not callable" error when trying to send email with attachments using python smtplib from gmail. I have enabled allow less security app setting on in sender gmail

Code:

import smtplib
from email import MIMEBase
from email import MIMEText
from email.mime.multipart import MIMEMultipart
from email import Encoders
import os

def send_email(to, subject, text, filenames):
    try:
        gmail_user = '[email protected]'
        gmail_pwd = 'xxxx'

        msg = MIMEMultipart()
        msg['From'] = gmail_user 
        msg['To'] = ", ".join(to)
        msg['Subject'] = subject

        msg.attach(MIMEText(text))

        for file in filenames:
            part = MIMEBase('application', 'octet-stream')
            part.set_payload(open(file, 'rb').read())
            Encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment; filename="%s"'% os.path.basename(file))
            msg.attach(part)

        mailServer = smtplib.SMTP("smtp.gmail.com:587") #465,587
        mailServer.ehlo()
        mailServer.starttls()
        mailServer.ehlo()
        mailServer.login(gmail_user, gmail_pwd)
        mailServer.sendmail(gmail_user, to, msg.as_string())
        mailServer.close()
        print('successfully sent the mail')

    except smtplib.SMTPException,error::

        print str(error)


if __name__ == '__main__':
    attachment_file = ['t1.txt','t2.csv']
    to = "[email protected]" 
    TEXT = "Hello everyone"
    SUBJECT = "Testing sending using gmail"

    send_email(to, SUBJECT, TEXT, attachment_file)

Error : File "test_mail.py", line 64, in send_email(to, SUBJECT, TEXT, attachment_file) File "test_mail.py", line 24, in send_email msg.attach(MIMEText(text)) TypeError: 'LazyImporter' object is not callable

1
Change import to from email.mime.text import MIMEText, because now you are importing module which is not callable - How about nope
@ How about nope, tried with from email.mime.text import MIMEText. Still getting same error. - Sum
probably you are getting it now in line: part = MIMEBase('application', 'octet-stream') - the same story as above, change to from email.mime.base import MIMEBase - How about nope
@How about nope. The code is working now after making changes in import as suggested by you. - Sum

1 Answers

1
votes

Like @How about nope said, with your import statement you are importing the MIMEText module and not the class. I can reproduce the error from your code. When I import from email.mime.text instead, the error disappear.