How to Send Emails Using Python - Plain Text, Adding Attachments, HTML Emails, and More
31:56

How to Send Emails Using Python - Plain Text, Adding Attachments, HTML Emails, and More

Corey Schafer 18.03.2019 479 556 просмотров 10 065 лайков

Machine-readable: Markdown · JSON API · Site index

Поделиться Telegram VK Бот
Транскрипт Скачать .md
Анализ с AI
Описание видео
In this Python Programming Tutorial, we will be learning how to send emails. We'll start with simple plain text emails and then learn how to construct more advanced messages. We will learn how to attach images, PDFs, create HTML messages, and more. Let's get started... The code from this video can be found at: http://bit.ly/python-emails Google Account Settings: https://myaccount.google.com/lesssecureapps https://myaccount.google.com/apppasswords Environment Variables (Windows) - https://youtu.be/IolxqkL7cD8 Environment Variables (Mac and Linux) - https://youtu.be/5iWhQWVXosU Lists Tutorial - https://youtu.be/W8KRzm-HUcc ✅ Support My Channel Through Patreon: https://www.patreon.com/coreyms ✅ Become a Channel Member: https://www.youtube.com/channel/UCCezIgC97PvUuR4_gbFUs5g/join ✅ One-Time Contribution Through PayPal: https://goo.gl/649HFY ✅ Cryptocurrency Donations: Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3 Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33 Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot ✅ Corey's Public Amazon Wishlist http://a.co/inIyro1 ✅ Equipment I Use and Books I Recommend: https://www.amazon.com/shop/coreyschafer ▶️ You Can Find Me On: My Website - http://coreyms.com/ My Second Channel - https://www.youtube.com/c/coreymschafer Facebook - https://www.facebook.com/CoreyMSchafer Twitter - https://twitter.com/CoreyMSchafer Instagram - https://www.instagram.com/coreymschafer/ #Python

Оглавление (7 сегментов)

Intro

hey there how's it going everybody in this video we're going to be learning how to send emails with Python so we've sent emails and previous videos but in this video we're gonna look at this more in depth and see how to use best practices and we're also gonna look at how to do more advanced emails such as adding attachments or sending HTML messages so let's go ahead and get started so first of all you're going to want to have an email account to send emails in this video we're going to be using Gmail which most of you are likely familiar with but you can use any email service that you'd like but the setup might be slightly different from this video if you're using a different service now we're also going to see how we can use your localhost to send test emails if you don't have an actual email address setup yet but for now let's look at some stuff that we need to do to get an account ready so for example if you're using Gmail then there are a couple of settings that you need to change in order to send emails through python using this account so let me pull these up in my browser so one is this my account google. com ford slash less secure apps so first if you don't have two factor authentication setup then you're going to need to allow less secure applications like python to connect to your account and you can do that at this URL here and I'll have links to these pages in the description section below if you want to access these URLs now if you do have two-factor authentication which I would always recommend then instead you'll need to create an app password so that you can connect through Python and you will do that at this URL here my account google. com forge / app passwords so you can see that I have an app password here called Python test and this is what I use to connect to my account now I've placed that password into an environment variable so that I never need to add it directly into a Python script I think it's a good habit to never add your sensitive information directly to your script but instead you should use configuration files that don't get committed to source control or use environment variables so if you've never used environment variables to hide information like this then I do have a separate video that shows how to do that for Mac Linux and windows so I'll leave a link to those videos in the description section below if anyone would like to see how that's done ok so once you've got an email account and you have your security settings in order let's see how we can send some emails so I have an empty Python script pulled up here in sublime

Connecting to Mail

text and you can create an empty script in the editor of your choice now just one tip if you're writing a script to test these things then don't call your script email dot pi because that will conflict with the module built in to the standard library so I have mine called mail - demo dot pi ok so first let's connect to the mail server now there are two different classes that we can use to do this and both of those are going to be imported from the SMTP lib module so I'll just import that entire module so I'll say import SMTP lib so first I'm going to go ahead and connect using plain old SMTP so I'm going to use a context manager here and using a context manager well make sure that our connection is closed automatically without us needing to do it manually so I'm just going to say with SMTP Lib dot SMTP so we're using the SMTP class there and now we'll put in the mail server that we want to use if you're using Gmail then this will be smtp. gmail. com so make sure that's spelled correctly and now we're going to put in the port number that we want to connect to and if you're using plain old SMTP then that's going to be 587 and now we can give this connection a variable name and I'm just going to call this SMTP and now within this with statement we're going to say SMTP dot and the eh ello method just identifies ourselves with the mail server that we're using and I think this is actually gets called automatically in the background anyways but just in case I'm going to go ahead and run this explicitly here and now we want to encrypt our traffic so we can say SMTP dot start TLS ok and now that we've encrypted to traffic we need to rerun the eh ello method again to re-identify our cell as an encrypted connection so I'm just going to copy this here and paste this in to run that again and now that we're encrypted we can go ahead and login to our mail server so I'm gonna say SMTP dot in and now we can put in up sorry that's going to be a method and now we can put in our email address and password that we want to login with now you can put this directly into the script but remember I said that I think it's a good idea to get into the habit of putting sensitive information into environment variables so that's where I currently have mine so at the top of my script I'm going to go ahead and grab these environment variables so I can do that with the OS module so above SMTP here I'm going to import OS and now here at the top of the file I'm going to create some variables using these environment variables so the first one I'm going to call email address and I'll set this equal to and to grab environment variables in Python we can say OS dot environment and I called my environment variable email underscore user and I'm gonna do the exact same thing for the password so I'll call this one email password and I call this environment variable email underscore pass so now I'm going to login to the gmail server using those credentials so I'm going to copy my email address and that is the first argument that we pass in to login and we pass in the password as the second argument okay so now that should log us in to our mail server now in my case I have two factor authentication so the email address is just simply my email address and the password here is the app password that I created through that app passwords page that I showed you earlier in the video okay so now let's create a simple message so we're going to see more organized ways to create messages and just a bit with other modules but if we want to create a simple message without importing anything else then we can do that so let's go ahead and do that first so first I'm going to create a subject for our message so I'll so a subject is equal to and I'll just say grab dinner this weekend and now I'll put in a body so for the body I'll say how about dinner at 6:00 p. m. this Saturday okay and now I can combine these into a single message now when you're constructing a plaintext email from scratch you need to add the subject as a header and then have a couple of blank lines and then put the body of the message so I'm going to do this using an F string so I'm going to say msg is equal to and now I'm going to create an EPS tring so we'll put an F there and now we need to put the subject as a header so I'll say subject and then put in our subject there and now we need a couple of blank lines and now we can put in the body of our message now I know that looks a little strange and it's a weird way to format a message but we are going to see more convenient ways to do this later in the video but if you're going to do it without any additional modules then you have to do it this way now if you've never used f strings before then you can use regular string formatting there as well now but basically you just need your subject those two new lines and then your body okay so now we can send this simple plain text email so to do this I can just say SMTP dot sin mail and now the format that we are going to use for this we is going to be the sender then the receiver and then the message so for the sender we want the sender to be the email address that we logged in as for the receiver I'm actually going to send this to myself so I could put email address here as well but just to kind of differentiate these two I'll just put my email address and manually to make it look like I'm sending it to someone else so my email address is khorium Schaefer at gmail. com okay now if you're testing this on your machine then you know I'd appreciate it if you didn't set my email address as the receiving address there I don't mind getting questions and messages from you all but if you're just going to be using this for a test then you know I'd rather not be bombarded with a lot of those test emails so you know if you don't mind please change that to your own address for testing purposes okay so for sending simple plain text emails then it's just as simple as this so if I save this then we can see if I scroll up here we've done this in 20 lines of code so now I can go ahead and run this and we didn't have an output so that's fine we didn't print anything but if I go back to my

Using a Local Debug Server

browser here then if I pull up my email here then we can see that I got my message so that's good now your if you're doing a lot of testing and don't actually want to send yourself an email each time then you can use a local debug server to test this so next we're gonna take a look at how to do that but quickly just to make sure that this all looks well let me open this up so that's our subject looks good our body looks good okay so I'm going to go ahead and delete that and now like I was saying now let's go ahead and take a look at how to use a local debug server to test these emails if you don't actually want to send yourself a bunch of emails so in order to do this I'm going to open up the terminal here so I open up a new terminal let me re size my terminal here and I'm just going to minimize this browser here in the background okay so we can start a debug mail server on our localhost by saying Python 3 if you're on Windows or if you're in a virtual environment then that might just be Python I'm on a Mac so I have to say Python 3 when I'm in my global environment so I say python 3 - M SMTP D so not just SMTP or SMTP lib but SMTP D and then - C and this will be d bugging server all one word with those capitalizations there and now - in localhost and then we will run this on you know port 1025 so if I run that then that will now listen for emails on our local machine and when it gets it we'll just print it out here to the terminal and then discard it so let's go back to our code and send an email to this debug server so I'm going to open up sublime and to do this I'm going to close our current output now I'm just going to comment out the current SMTP connection that we have with Google and just create a different one so I'm going to copy this and comment out the current one and just paste in another one here underneath it and instead of connecting to the Google Mail server I'm just going to connect to local host on port 1 0 to 5 so instead of Gmail here I'm just going to say local host and that's going to be on port 1025 okay and with the debug server we're not going to be able to start TLS or login so I'm just going to comment out those lines as well so I'm and now all we have is our message creation and the send mail so now if I run this code then again we don't have any output but if I go back to the terminal then we can see that message was printed out to our terminal instead of actually sending an email so that's a way that we can test these messages if we don't want to keep sending emails to ourselves ok so I'm going to go back now and undo those changes and I'm just going to go back to sending real emails for the purpose of this video so I'm going to shut down the terminal here and go back and just undo all of those changes that I made and save that ok so now let's take a look and see how we can make this a bit easier on ourselves and how we can send more complex messages so first of all I feel like this part here at the top of our context manager is a bit weird where we are you know sending the eh ello then the start TLS and then the eh ello again now if we wanted to then we could just use the SMTP SSL class to have an SSL connection from the very beginning and then we won't have to run these other commands so to do this instead of using the SMTP class I'm going to use SMTP underscore SSL and when you use an SSL connection that instead of this being on port 587 we're now gonna use port 465 and now we can remove these other lines here so I'm just going to and now we're just simply logging in and sending our message so if I save this and go back to my browser here then we can see that still

Formatting the Message

works - I still got that new email okay so the other thing that's a bit weird back in our code let me delete that test email so that we're sure that we're working with a clean slate let me go back to the code okay so another thing that is a bit weird is the formatting that we're using with our message it's not really intuitive that we have our subject and then the two blank lines and then our body so let's see a better way to do this so I'm gonna make another import here at the top and I'm going to import a class called email message and that is from email dot message import and this is email whoops email message so this is an email message class and now we can use this email message to set these things a bit more cleanly and we don't even need to create this message inside of our width statement so let's instead build this up at the top of our file here and then just use our width statement to log in and send the message so up here underneath our email address and password I'm going to create a new email message so I'm going to say message is equal to email message and now instead of creating these different parts of the message separately and then combining them I'm instead just going to set these on our message object itself and I'm also going to add the sender and receiver to the message object also so we can simply say so I will copy this here and now to set the subject we can just set the subject directly like this so I will copy our old subject here and paste it in and now I'll get rid of that subject line and now I'm also going to put the sender and receiver inside the message itself so to set the sender and receiver this is going to be a from right here so we can set the from to our email address and we can set the message and access this to key there and we're going to set the two to be to Cory M Shaffer at gmail. com okay and now we can actually set the content of our message which is going to be our body so I can say MSG dot set underscore content and now we can pass in the content of our message so I'm just going to copy the same one that we had before and now I can get rid of our body down here message down here and also when we send mail and instead of using the send mail method since we're no longer using the sender and receiver within this instead we're going to use the send message method because all we're doing is sending a message so I'm going to get rid of those and just have the message there and this is going to be send underscore message okay so I think that this organizes the information for our message a little bit better so now we have it all in one place and not only that but this is also going to let us put together some more complicated messages as well with us doing it this way but if we were to run this right now then we should still just get that same plain text email that we got before so I'm gonna save this and run it and now if I check my browser here and email then we can

Adding Attachments

here and if I check my email then we can see that we got that same plain text message that we got before so that's still working okay so now let me go back to our code okay so now we're using this new email message object to send our message so now let's see how we can add some attachments to this email so I have some pictures of my dog when he was a puppy saved in the same directory as this script so let's say that I wanted to add those as an email attachment so first I'll just attach one image and then we'll see how to do two after we send the one so first I'm going to change the subject of subject and the body of our message here so I'll just say check out Bronx as a puppy and then for the content here I will just let them know that there's are an image attached so I'll just say imaged attached here okay so now below set content here I'm going to open that file that I want to attach so to open this file I can just say with open and this file is in the same directory as my current script that I'm running so I don't have to set a full path or anything but you would set the full path to the image that you want to attach and this image for me is called Bronx one jpg so I'm going to open that as in our B mode which is read bytes and I will just call this F so now within here I can read that image data so I'll say file data is equal to F dot read and now we can attach this to our message but before we attach this we're going to need to be able to determine what kind of image were attaching so if we're just doing one image then we could put this in manually but if you're doing multiple images then you're likely going to want Python to determine this for us and there's a built in module that can do this for us and that's the image HDR module so to import this I'm going to go up here to the top and I'm going to import oops import and this is I M G HDR okay and I'm just going to copy that module name here so that I don't spell it incorrectly and now to get the type of image that this is within our with statement down here where we have this image file open I'm going to say file underscore type is equal to IMG HDR dot what this is a dot what method and now we can just pass in that it that name of that file so I'm going to say F dot name so we're passing in the name of the file now you could also change that up a bit in order to get the image type by reading in the image bytes but in this case I think it's just easier to do it with the file name so just to show you what this does if I comment out everything underneath this so I'm not going to send an email right now I'm just going to print out this file type and see what Python gives us here so if I run this then we can see that the output that we got that it returns JPEG so that worked because it is a JPEG image okay so now let's attach our image to our message so I'm going to remove this print statement here where we printed out that file type I'm going to uncomment out everything here let me just get that up there okay so now that we've set that file data in that file type now below that with statement and outside of the West statement we're back on the main level of our code here I'm going to say MSG dot add underscore attachment and what we want to add is that file data whoops file data and now we want to say main type is equal to and this is an image and it also needs a sub type so I'm going to say sub type is equal to and that is what kind of image it is so I want to pass in file type as the sub type okay so that should attach that image now we also want the name of the image for our attachment so I'm going to go ahead and grab that too so up here underneath file type I'm just going to say file name is equal to F dot name so let me pass this in as well so another argument to add attachment I'm going to say file name is equal to file name now I named my variable file underscore name and the argument here is just file name one word so keep that in mind if you're following along okay so that should add our image as an attachment to our email so if I spelled everything correctly if I save that and run it so we don't have any output but if I go back to our browser here and check this now this

Sending Images

might take a second because we're sending an image instead of plain text okay so we can see that just came in so if I check this then we can see that we have our subject as check out Brock's as a puppy our body is image attached and if I open this then we have the image that we attached to the email and if I check the name of this image if I just hover over this then it also got the image name of that file as well so this is Bronx one dot jpg okay so let's go back to our script okay so now that we've attached one image let's see what we do in order to attach multiple images so you can simply create a loop while making these attachments in order to do this so above the with statement I'm going to say files are equal to and I'm going to create a list of file names here and these are going to be the list of file names that I want to attach to my email so one is going to be Bronx one dot jpg the other one is just called Bronx underscore two dot jpg and now I'm going to say for file in files indent this with statement here so that we're getting this information for both files now I'm also going to indent my message add attachment into our for loop so that we're attaching both of these and also we need to change the file name that we are opening so right now we're just opening this Bronx one dot jpg we want to just open file so when it loops through this we're going to open Bronx one dot jpg read in that data get the file type get the file name and attach that to our message and then it's going to move on to Bronx two jpg get the file data file type file name and then add that as an attachment to our message so if I save that and run it then this one will probably take even longer to come in now but if I check the browser then let me go back to my inbox and it looks like this came in here so now we have two attachments so we have Bronx one jpg and that came in with the right file name and we have Bronx two jpg and that came in with the correct file name as well so now I'm going to delete both of these just to clean that up a bit go back to my code okay so attaching both of those images to our email worked well now if you're attaching some other kind of file then you just need to change the main type the subtype for each one so I also have a PDF on my or in the same directory as my script here so if I wanted to send something like a PDF then I could go ahead and do something like this so I'm just going to keep my for loop here but for the files up here I'm just going to make this a list of one file and I called this resume dot PDF so now that's going to loop through here it's just once because there's one PDF file it's going to open it read in the data read in we don't need the file type anymore because it's not an image so now we can just have the file data and the file name and now for the when we add the attachment what we're going to do here as the main type is we're going to say application and for the subtype I'm going to put in a string here and this is going to be octet - string so make sure you can see both of those there now by setting the application as the main type and octet stream as the subtype that's what the Python documentation calls a generic bag of bits type so basically just generic information for that so if I save that and run it then let's go back to the browser here and let's see if we got

Sending Multiple Emails

this message and we did I forgot to change the subject here from check out Broncs as a puppy but if we look at the resume then we can see that we do have this resume PDF here and we do have that PDF file so that works well ok so now let's look at a couple more tips here that you might find useful when sending emails so first let's say that you want to send emails to multiple people that's fairly common now in order to do that it's as simple as passing in a list where we currently have the receiver so let me make a list here so I'm going to go up here to the top now above my message here I'm just going to create a list and call this contacts and set this equal to and I will my email address and then you can pass in what other email address that you want to send this to so test at example. com or something like that and now when you do the message too we could pass in that list of contacts now when I was making this video I tested this with my email and the email of a friend of mine and it worked well it did send emails to both of us but this isn't how they have it in the Python documentation so I'm not sure if this is frowned on for any reason but in the documentation they have it where they are passing in a string of comma separated values so I could do this manually by adding a string with both of these email addresses comma separated or if we wanted to create a comma separated string from this list then we could do that simply by saying we could do a comma there as a string and then say dot whoops dot join and we want to join that contacts list now I know that looks a little confusing there if you've never used it if you've never seen a joint statement like that then you can watch my video on lists for more details on how that works so those are some ways of how you dad multiple recipients to an email but for now I'm just gonna set this back to send this just to myself so I will just put back in my email address here instead of using those contacts okay so the last thing that I want to show here in this video is how to send an email with HTML so this is common for newsletters and things like that where you want to spice it up a bit and have a better presentation than just plain text email so in this email that I'm gonna send I'm gonna have HTML and plain text as an alternative because some people turn off HTML emails so you want to have that text as a fallback so I'm just going to delete the part where I added the attachments here so I'm going to delete all the way down from the files to the attachments now for the message set content I'm just going to have this be the plain text so within here I'm just going to say this is a plain whoops plain text email and now to set the HTML message I'm gonna use a small HTML snippet that I have open up here in sublime that just has a simple heading that is styled with a color so I have that open here and if you want to use this simple HTML to test this out for yourself then I'll be sure to add that to my github and leave a link to that in the description section below if you would like to use this as well so I'm just going to copy this email here and now go back to the script and now let's add that email to our or let's add that HTML to our email so to do this I can simply say MSG dot add underscore alternative and now within add alternative I'm going to put triple quotes here oops let me do double quotes here so triple quotes which means it's going to be a multi-line string and I'm gonna put a backslash there to cancel out that newline and now I'm just going to paste in that HTML and now so we this is kind of large here but when we add alternative this entire string here is our first argument to add alternative and now I'm going to put in a comma to add in one more argument and that argument is going to be sub type so that sub type is going to be equal to HTML okay so by adding that HTML as our alternative there and setting that sub type now if I save this and run it then let me go back to my email here and I will inbox and again I forgot to change this subject line but if I click on this then we can see that we got that HTML email and that the text has a h1 heading style with this blueish gray color so that hTML is working so that's good okay so now let's go back to my script and let me see if we can fit I don't think we can fit all of this on one screen here but if you need to see this hopefully you can see everything to create that message right there and I'll be sure to put this finish script on my github as well and leave link to that in the description section below if anyone would like to see this finished script okay so I think that is gonna do it for this video hopefully now you have a pretty good idea for how you can send just about any type of email that you'd want to send with Python but if anyone does have any questions about what we covered in this video then feel free to ask in the comment section below and I'll do my best to answer those and if you enjoy these tutorials and would like to support them then there are several ways you can do that these this ways to simply LIKE the video and give it a thumbs up and also it's a huge help to share these videos with anyone who you think would find them useful and if you have the means you can contribute to patreon and there's a link to that page in the description section below be sure to subscribe for future videos and thank you all for watching

Другие видео автора — Corey Schafer

Ctrl+V

Экстракт Знаний в Telegram

Экстракты и дистилляты из лучших YouTube-каналов — сразу после публикации.

Подписаться

Дайджест Экстрактов

Лучшие методички за неделю — каждый понедельник