How to Send Emails in Python

How to Send Emails in Python


In this video I’m going to explain how to
send emails with python. I’ll first explain how to setup less secure
apps, then how to make a basic email, then how to add an attachment and lastly using
HTML in an email. If you do not have a gmail account already,
go and create one. If you already have one, sign into it. Now go to less secure apps and login if needed;
the link will be in the desciption and in the article for this video. In this page you will want to flick the Allow
less secure apps switch to on. This now allows less secure sign-in technology
to login to the email server. Now open a new python file and save it. First import smtplib and then import MIMEText
from email.mime.text and MIMEMultipart from email.mime.multipart. Next we will set some varaibles; set email
to your gmail address and set password to the password of the email address. Then set send_to_email to the email adress
you want to send the email to, set the subject to what you want in the subject line and set
the message to the content of the email. I will be sending the email to myself for
this demonstration but when sending an email, you will want to make sure send_to_email is
who you want to send the email to. Now create a new instance of MIMEMultipart
and set it’s ‘From’ index to email, ‘To’ index to send_to_email and ‘Subject’ to the subject. Attach the message using a MIMEText object
while declaing it as plain text. Now create a connection to Googles smtp server,
start ttls and login using the username and password you declared at the top. Set text to the created message as a string
and then send the email using sendmail passing your email address, the email address you
want to send the email to and the text varaible we just created. Finally close the connection to the server
using .quit(). Save and run this script and look at the recipients
email account. You should see that you have recieved the
email with the subject and message provided. To add an attachment to the email go back
to the top and import MIMEBase from email.mime.base, encoders from email and os.path. Now declare a new varaible at the top called
file_location which tells the script exactly where your file you want to attach is located. After attaching the message previously, create
a varaible called filename and set it to the result of os.path.basename when passing the
file_location; this will be the filename displayed to the recipient. Now open the file using read binary and create
a MIMEBase object passing application and octet-stream as string arguments. Using the set_payload method on this object,
pass in the contents of the file we just opened and then encode the object using base64. Now add a header to this called Content-Disposition
declaring it is an attachment and providing it’s filename. Attach the MIMEBase object to the MIMEMultipart
object we have previously attached the message to. You can now save and run this script. Looking at the recipients email, you will
be able to see that the file has been sent in the email. To make clickable links and be able to use
css in an email, you will need to write the email in html. Prepare your html code and assign it to a
varaible. Now you will want to assign another varaible
the plain text version of the html without any tags. Go to the declaration of the MIMEMultipart
object and pass the string ‘alternative’ to it. We will now attach the html and plain text
like we did before, but this time we will provide a type of html when attaching the
html message content. When saving this and running, we can then
go to gmail to make sure that its worked. We can see that the link is clicable showing
that html code is present in the email. This shows that we can use html in emails;
be aware though, not all parts of CSS and HTML can be used in emails. To look at what can and cannot be used, go
to https://caniuse.email/. If you want the code for this video or a written
tutorial, go to the link in the description. Also if you have any questions, leave them
in the comments and I will try to get back to you when I can. If you want to recommend a possible topic
I could cover, put it in the comments and I will look at them also.

42 comments

  1. it is very useful thanks
    i was just watching your video about mouse simulation and i have some question if you don't mind can i have your email or any thing to communicate with you

  2. Nice video <3
    Also could you make an "How to make a screenshot app/screenshot using python"?
    It would be nice
    I would integrate it into that keylogger xD

  3. I just want to say how much I appreciate your tutorials. Very concise, straight to the point and have exactly the information I need for my projects. Thanks!

  4. Another great video, it's very helpful. Any idea where to close the connection to the attachment. For example, attach_this_file.txt can not be modified after the email has been sent if the script is still running.

  5. This video is not working anymore because gmail doesn't allow to sign in from other app anymore and block the less secure app access.

  6. But my filename is non-ascii characters so when the email send the file, the filename of that file have noname. What to do? How to make it send the file with its filename as non-ascii characters?
    I am using pyV3.7

  7. sir i have been trying to run the login command for 2 hours…each time it gives me wrong credentials error …i have tried with multiple emails ….none of them i could log in …please help me somebody

  8. Thanks for the tutorial, but what about if I would like to send 250 emails from .xls or a .txt. What other lines would I need to add?

  9. Eventhough I turned on “less secure app” and when I tried sign-in from a new device and different location, google blocks the sign-in attempt and send me a message “Suspicious sign-in attempt prevented”. Please help. But everything is fine when I tried sign-in from the known device.

  10. Although i am not an Englishman, i`d like to say that your tutorial is the best i`ve seen. No sites could help, but you did. Thanks a lot

  11. Hmm… I think I messed up somewhere. (Everyone else is saying it works, so I pobably messed up.) I copied everything that you said. The error says:

    msg.attach(Mimetext(message, 'plain'))
    nameError: name 'Mimetext' is not defined.

    I put "from email.mime.text import MIMEText"

  12. Hey I just recently left a comment for an error in my server. I got it figured out. I'm 100percent new to any programming so trying my best. Thanks for the awesome vid.

  13. Hey cool video and nice coding. I have copied the exact code and i keep getting the error "TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
    "

    The prorgam runs for 20 seconds then closes and prints the error above. I have tried disabling firewalls but still nothing, what should i do?

  14. This is awesome! I love how easy it is to do and that no [non-pre-installed] modules are required. Thanks so much for making these tutorials, everyone appreciates them. Is it possible to read emails in Python as well? If so can you please make a video on it? Thanks so much again!

  15. Hello, pls support i am getting error

    = RESTART: C:/Users/GEMIS/AppData/Local/Programs/Python/Python38-32/sendemailwithpython.py
    Traceback (most recent call last):
    File "C:UsersGEMISAppDataLocalProgramsPythonPython38-32libbase64.py", line 510, in _input_type_check
    m = memoryview(s)
    TypeError: memoryview: a bytes-like object is required, not 'NoneType'

    The above exception was the direct cause of the following exception:

    Traceback (most recent call last):
    File "C:/Users/GEMIS/AppData/Local/Programs/Python/Python38-32/sendemailwithpython.py", line 25, in <module>
    encoders.encode_base64(part)
    File "C:UsersGEMISAppDataLocalProgramsPythonPython38-32libemailencoders.py", line 32, in encode_base64
    encdata = str(_bencode(orig), 'ascii')
    File "C:UsersGEMISAppDataLocalProgramsPythonPython38-32libbase64.py", line 527, in encodebytes
    _input_type_check(s)
    File "C:UsersGEMISAppDataLocalProgramsPythonPython38-32libbase64.py", line 513, in _input_type_check
    raise TypeError(msg) from err
    TypeError: expected bytes-like object, not NoneType

  16. Hi,

    Thank you. Your tutorial is clear and straightforward. Question, how do I put the content of a text file (ex. logfile.txt which is located in a certain directory) to the body of the email? Also, how do I add variable to the subject line of the email?

    Thanks in advance.

  17. I did this, but I keep getting an error. Im not sure how to fix this error
    "SMTP AUTH extension not supported by server.")

    smtplib.SMTPNotSupportedError: SMTP AUTH extension not supported by server.

Leave a Reply

Your email address will not be published. Required fields are marked *