Search code examples
pythonpython-3.xemailmime

Emailing with an attachment with Python


import smtplib
import mechanize
import os
from email.mime.multipart import MIMEMultipart 
from email.mime.text import MIMEText 
from email.mime.base import MIMEBase 
from email import encoders 

def sem():
    if not os.path.isfile('key.txt'):
        print('below details are req to send report')
        gmail_user = input('enter your email=')
        gmail_app_password = input('enter your email password=')
        print('pls accept the login in your gmail account ')
        ke = open('key.txt',mode="w+") 
        ke.write(gmail_user)
        ke.write(':')
        ke.write(gmail_app_password)
        ke.close()
    if not os.path.isfile('sto.txt'):
        gmai = input('enter the  email to send report=')
        ke = open('sto.txt',mode="w+") 
        ke.write(gmai)
        ke.close()


    with open('key.txt',mode="r")as f:
        ds=f.readlines()
        d=''.join(ds)
        r=d.split(':')
    with open('sto.txt',mode="r")as f:
        ds=f.readlines()


    f=ds
    print(f)
    gmail_user = r[0]
    gmail_app_password = r[1]



    sent_from = gmail_user
    sent_to = ds
    sent_subject = "hey amo lio ,how are ?"
    sent_body = ("Hey, what's up? friend!")

    email_text = """\
    To: %s
    Subject: %s

    %s
    """ % (", ".join(sent_to), sent_subject, sent_body)
    mail = MIMEMultipart()
    mail["Subject"] = sent_subject
    mail["From"] = sent_from
    mail["To"] = sent_to
    mail.attach[MIMEText(sent_body,'html')]

    ctype, encoding = mimetypes.guess_type(_file)
    maintype, subtype = ctype.split('/', 1)
    fp = open("./data/mood.txt")
    msg = MIMEText(fp.read(), _subtype=subtype)
    fp.close()
    filename = os.path.basename(_file)
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    mail.attach(msg)
    print('done')
    server.sendmail(sent_from, sent_to, mail.as_string())
    try:
        server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
        server.ehlo()
        server.login(gmail_user, gmail_app_password)
        server.sendmail(sent_from, sent_to, email_text)
        server.close()

        print('Email sent!')
    except Exception as exception:
        print("Error: %s!\n\n" % exception)

sem()

How can I attach the helloword.txt file in this email? This code is working fine, I just want to send an attachment along with it. This code lets me me send the body without any attachment. Also, how do I encrypt the key.txt file which store email address and password, and to send email it it requires the password to be entered (diff pass)?


Solution

  • You need to use the 'MIMEMultipart' module to attach files.

        from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    
    mail = MIMEMultipart()
    mail["Subject"] = sent_subject
    mail["From"] = sent_from
    mail["To"] = sent_to
    mail.attach(MIMEText(sent_body,'html'))
    
    ctype, encoding = mimetypes.guess_type(_file)
    maintype, subtype = ctype.split('/', 1)
    fp = open("/path/to/attachment/file.txt")
    # If file mimetype is video/audio use respective email.mime module. 
    # Here assuming 'maintype' == 'text' we will use MIMEText
    msg = MIMEText(fp.read(), _subtype=subtype)
    fp.close()
    filename = os.path.basename(_file)
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    mail.attach(msg)
    
    
    server.sendmail(sent_from, sent_to, mail.as_string())