2
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)?

anshul raj
  • 125
  • 9

2 Answers2

3

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())
PN7
  • 117
  • 1
  • 11
  • mail.attach[MIMEText(sent_body,'html')] TypeError: 'method' object is not subscriptable – anshul raj Jun 05 '20 at 04:31
  • check i updated the code, the above error is showing , im trying to solve it from 2days @PN7 – anshul raj Jun 05 '20 at 04:35
  • Hi, mail.attach[MIMEText(sent_body,'html')] should be mail.attach(MIMEText(sent_body,'html')) – PN7 Jun 06 '20 at 05:58
  • hi bro ,I went to many documentation around google and different code but I could not solve the following error **ctype,encoding = mimetypes.guess_type(_file) NameError: name 'mimetypes' is not defined** idk whats the error but it will be really helpful if u help me out , and thanks for the help – anshul raj Jun 13 '20 at 04:11
  • 'mimetypes' is a python module. Just 'import mimetypes' – PN7 Jun 13 '20 at 14:51
1
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 
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import mimetypes
import pdb

def email:
    sender_address = gmail_user
     #make it input
    receiver_address = gmail_user
    #Setup the MIME
    fromaddr = gmail_user
    sendto =  gmail_app_password
    sender_pass = gmail_app_password = input('enter your email password')
    msg = MIMEMultipart()
    msg['From'] = fromaddr
    msg['To'] = sendto
    msg['Subject'] = 'This is cool'
    body = "this is the body of the text message"
    msg.attach(MIMEText(body, 'plain'))
    filename = 'mood.txt'
    attachment = open('./data/mood.txt', 'rb')
    part = MIMEBase('application', "octet-stream")
    part.set_payload((attachment).read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename= %s' % filename)
    msg.attach(part)
    smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
    smtpObj.ehlo()
    smtpObj.starttls()
    smtpObj.login(gmail_user, gmail_app_password)
    text = msg.as_string()
    smtpObj.sendmail(fromaddr, sendto , text)
    smtpObj.quit()    # attach the instance 'p' to instance 'msg' 

here is perfect working code for sending email

anshul raj
  • 125
  • 9