Milteven
Milteven

Reputation: 31

Python: Trying to send attachments via email ~ string error?

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?

Upvotes: 1

Views: 1306

Answers (1)

Eugene Morozov
Eugene Morozov

Reputation: 15816

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.

Upvotes: 1

Related Questions