The below article will help you understand how can you send an email reading a content from a text file as body of the email. We are using smtplib package of Python for the same.
This program is quite simple. We ask from the user the email address of the person to whom we want to send the email and the path of the text file on the local system from which we want to read the contents and send it as email body. Once user confirms it, the prepareContent function is called which reads the content of the text file from the path given whereas sendEmail function sends the email with the appropriate content.
import sys import smtplib def prepareContent (textFilePath) : with open(textFilePath, 'r') as content_file: content = content_file.read() return content def sendEmail(emailAddress, content) : gmail_user = "email_address" gmail_pwd = "password" FROM = "email@example.com" TO = [emailAddress] SUBJECT = "Test Email" TEXT = content message = """From: %s\nTo: %s\nSubject: %s\n\n%s """ % (FROM, ", ".join(TO), SUBJECT, TEXT) try: server = smtplib.SMTP("smtp.gmail.com", 587) server.ehlo() server.starttls() server.login(gmail_user, gmail_pwd) server.sendmail(FROM, TO, message) server.close() print 'successfully sent the mail' except: print "failed to send mail" if __name__ == "__main__": emailAddress = sys.argv textFilePath = sys.argv print "Email Address is : ", emailAddress print "Path of text file is : ", textFilePath var = raw_input("Is this information correct ? Do you want to continue ? (y/n): ") if var == 'y' or var == 'Y' : content = prepareContent(textFilePath) sendEmail(emailAddress, content)
I got one error while logging in to the server on the line,
The error read,
File "", line 1, in File "/usr/lib/python2.7/smtplib.py", line 622, in login raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (534, '5.7.14 ......
I also got an email on my yahoo id (which was my backup id for gmail) stating that :
Hi ronak, Google just blocked someone from signing into your Google Account ***@gmail.com from an app that may put your account at risk.
According to Google, the way we are signing in into Google is less secure and it falls under less security apps. They also provided me with a link with which I could enable this app to access my mail. I just turned on the access for less scure apps and ran again. It ran smoothly this time without any error.