1

I'm trying to send attachments via email with python but I'm getting this error:

msg.attach(msgImage) AttributeError: 'str' object has no attribute 'attach'

Here is the code:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.mime.image import MIMEImage


def send_email():
    fromaddr = '[email protected]'
    toaddrs  = 'Toemail'
    global msg
    subject = 'RESPOSTA'
    message = 'Subject: %s\n\n%s' % (subject, msg)

    username = '[email protected]'
    password = 'xxxxxxxx'

    server = smtplib.SMTP('smtp.gmail.com:587')
    server.starttls()
    server.login(username,password)

    fp = open ('C:\Python27\Scripts\pares.txt', 'rb')
    msgImage = MIMEImage (fp.read(), _subtype='txt')
    fp.close()
    msg.attach(msgImage)

    server.sendmail(fromaddr, toaddrs, message,  msg.as_string())
    server.quit()

msg = 'Email test, please, see the attachments'
send_email()

Anyone has a hint of what is the problem?

2
  • Hint: What's the type of msg? Commented May 9, 2017 at 14:18
  • 1
    msg is a string, but I still don't understand the problem, when the script reads the txt file, is it no able to "attach" the content as a string? Commented May 9, 2017 at 16:45

1 Answer 1

1

Your code is weird and incorrect. You start using advanced concepts without a basic knowledge of the language, smtp protocol and email module.

msg variable in your code has str type. str is a plain string - a list of characters. It doesn't have method .attach.

I guess you wanted to use an instance of the class email.message instead of a string. Also, there's no need to use global variable. Global variables are bad, and it's totally unnecessary to use global variable in your case.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the Answer, i'm using a global variable because maybe in the future it will be used in another function.
If you want to write a function that is later to be used by another function, then global variable is the worst possible way of passing parameters. You need to use normal function parameter, not a global variable. For example: def send_mail(msg):

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.