Facebook

How to send email using python

To send the mail to multiple people using code is easy. Copy paste the below line in a text file and save as mail.py.  Replase the me@gmail.com with your actual email address and you@gmail.com with the address to whom you want to send the email.

Make sure your access level settings in gmail account are set to low.
go to this link https://www.google.com/settings/u/1/security/lesssecureapps
and check radio button 'Turn on'.

# code starts here ...

import smtplib

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# me == my email address
# you == recipient's email address
me = "me@gmail.com"
you = "you@gmail.com"

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you

# Create the body of the message (a plain-text and an HTML version).
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """\
Your html content goes here...
"""

# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

# image attachment code here

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
# Send the message via local SMTP server.
mail = smtplib.SMTP('smtp.gmail.com', 587)

mail.ehlo()

mail.starttls()

mail.login('username', 'password')
mail.sendmail(me, you, msg.as_string())
mail.quit()

# code ends here ...


You can also attach file/images to your email.  Use the below code snippet for same.

#attaching an image as attachment. START

ImgFileName = '/home/rana/Pictures/1.jpg'
img_data = open(ImgFileName, 'rb')
image = MIMEApplication(img_data.read(), Content_Disposition='attachment; filename="%s"' % basename(ImgFileName), Name=basename(ImgFileName))
msg.attach(image)

#attaching an image as attachment. END

You can use for loop to send the same mail to multiple people. That part I leave up to you.


If you face any issue while sending mail using this code, let me know.






Finding file and directory in ubuntu


To find a file in your system by name use below command -

find -name "query"

For case insensitive search -
find -iname "query"