Sending Emails With Python Including Attachments (New Method for GMail - 2022)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
foreign today we are looking at emailing from a Python program now in my day job I make a lot of machines and Jazz and it is very useful to have them email you from time to time whether that's daily data dumps or just when something's gone wrong you need to get to site to fix it to do this we'll need to set up our email for SMTP or simplemail transfer protocol as the name suggests it's nice and simple for this we'll be using Google as the SMTP server now one of the reasons I'm making this video is they've recently updated how this service works on their back end so if you made Auto emails before and for some reason they've just start working that is why so welcome to my world so in short today we'll be setting up our email to be able to actually automatically send these SMTP emails we'll be writing some basic code to just send text emails and we'll be getting into a little more depth to be able to send emails with attachments for example CSV files okay so let's get to it [Music] okie dokie so the first thing we want to do is come into our email account to actually enable us to do SMTP emails as I've said we're doing this in Google and using the Google SMTP server so you come up here and you click on your little icon and you go to manage your Google account once you're in here click on security and then scroll down should say as well to do this you need to have two-step verification on I won't go into it in this video but if it's not on you won't have this app passwords selection thing here when you set it up this guy appears so we're going to click on app passwords pop in our email s are in we have this little uh this little menu we're going to select the app we want to do which is uh we'll just put other for this and we'll this bit is just for your own reference just so if you've got a bunch of them you can know which password is which all right so SMTP email I'm just going to click generate now this is a kind of a crucial bit this is the one and only time you will be able to see this from Google anyway so you need to copy this and put it somewhere safe so in emails this is just a little folder I've made for uh for this little project I'm just going to make a text file foreign text save that and now we have that code and the second we press done you will never be able to see that from Google again if you lose it you'll have to delete this and create a new one um at the end of this video I'm going to be showing you how to come back in and get rid of this and by the time this video is up I will have done that so this code by the time you guys see it um you won't be able to send emails from my account you cheeky little buggers so let's uh let's crack on with the actual code [Music] okey dokey so first off we're going to have a crack at building a super simple just text email sender now these are great for when you just need some updates from something that's going on site so you know low oil level something's broken get the voice to site type email so I've made this little folder on the desktop the link to the GitHub of all of this will be in the description of this video as always uh so in here we've got the password that we just did before I have a random data CSV uh we'll get on to that in a moment and we have our two scripts which are just completely blank at the moment so the first thing we're going to want to do is import our library so we're going to need two libraries for this which is the SMTP lib and SSL so pop those in now easy and now we want to do is set up our port and server number so we're going to set these up as variables you can call them whatever you want but I'm going to call them SMTP port and SMTP server okay so now we've uh we're putting our port and our server the port we have put 587 which is just your standard secure SMTP port and the SMTP server that is a strength that we're we're making and that string is smtp.gmail.com so that is uh just letting us while letting the program know that this is the the SMTP server that we want to be using and hence us configuring our Google Gmail stuff before and now this is super simple so we're just going to make a message that uh that pops up uh in the email now these are usually for when something goes wrong so I'm just going to pop in dear God please help so something's gone wrong so next thing we want to do is create an object uh that is uh the context of this of this email so we're going to just call this uh simple email context I'll talk through when I've got it down Okay so we've made this thing called Simple email context and that is ssl.create default context which is one of the things from uh from this import SSL Library and now we've done that we can move on to actually connecting to the server and uh and sending these emails and we do that by trying to connect to the server so let's give that a go all right so what we have done here is we've um given the uh well making a server object called tie server and we're calling on this SMTP library to create the create this connection so using these guys up here and now we want to uh start this TLS using this context here so that's just fell in here it looks a bit weird but context equals c book simple simple context and now we want to log in using the credentials that we set up before so we're going to come back up here and just add in our email address and we're also going to put in the email that we want to send it to and also the password so just give me one moment all right so we're going to be emailing from our email to our own email obviously you'd put a different email if you want to send it to a different email should say as well this email I've just set up for YouTube feel free to email me at that address but I very very rarely actually check the mail in there so please don't be offended if I don't get back to you quickly now what we need to do is grab our password that we copied from Google before and paste it in here as a string now generally you don't want to do this this is just for demonstration purposes you want to reference this externally so you don't leave your password hanging around in your code but now we've done that for this login we can tell the login that we want to forgot to change that over we want to email from our email and we want to log in using this password and just some little printouts to let the user know what's going on and now we actually want to send our password itself so I'm going to use some F strings in this just to make it a bit clearer what's going on okay so this will just let us know that it's trying to send and is successfully sent if it does and in between these we're going to send the actual email and the arguments for this are the email that we're sending it from which is this and the email we're sending it to because we've already done all the login stuff up here you know of course it won't be an email without the message itself so our third argument is the message and that is that so this is a try except so we're just going to pop an accepting just to fire out what problem has happened if any so this will just give us a kind of an explanation what's happened if the email fails to send for any reason so either this is going to happen so sending it properly or not sending it properly but either way after we've done that we want to close off uh close off that Port close off the server so we're just going to do a finally so let's give this a save and we're going to bring over our terminal obviously we're in there in the same directory as this and we're just going to run we're going to run this python text underscore email dot py one thing to note because this really tripped me up when I was getting my head around all of this if you call that your script email.py which is very tempting it won't work it'll give some weird um weird failures uh on the log but it's just the name of the script itself it can't be email.py so don't name a function in their email as a function and don't use email as the name for a script because it's a bunch of reserved stuff that just trips you up to me a long time to work that out so let's run this code oh how silly of me these aren't strings one second okay let's try that again fantastic and if you heard my phone Buzz looks like it's worked so let's go check out our emails here we go so email from me no subject dear God please help so we've done it we have sent an email from python code so now it's delve a bit deeper and try and do it with a bit more uh behind it so we can put in subjects and we can actually attach useful stuff like CSV files and whatnot [Music] alrighty then so we can go over to our with attachment script empty as is what we can do actually is copy over a load of this stuff to to reuse it so we don't actually need this SSL library for this but we are going to need a few other libraries which I'll just pop in now all right so we're going to be using a library called uh mime for this so we just imported a bunch of stuff from there so my text my multi-part and my base and we've also imported this encoders thing which will allow us to encode it all uh in base64 for for sending over all the attachments and whatnot what I'm also going to do instead of sending um just to one person I'm Gonna Make a list just to show you how to to set this up to send it to a list of people rather than just one so I'm just going to send it to myself three times but obviously you can see how that works if you pop in different emails there and what we're also going to add is a subject which was lacking in the in the last one there we go so we're going to make ourselves a function to send this off I'll just pop that in now and again we're not calling this just email or emails because that causes problems so the function is called send emails and we're going to put in one argument for that and that is going to be this email too I'm going to change this to list so it's a bit clearer so this is going to be one of the arguments in that function and as We're looping through and sending these emails to different people we're going to set up a loop all right so what we're going to do here is set up the body of the email itself so we're going to call it body and this is just going to be an F string so this is just what is in the body of the email if you wanted to send any clever text a nice little trick we can do as well instead of sending it just as uh a string like that we can put three of these like that so now anything that we put inside of these uh these triple quotes air quotes um is going to have line breaks in as well so we can do line one line two so we can get a bit of a nice format in the email without having to put a load of backslash ends everywhere to make it look pretty and still with this you can also have an F beforehand make it an F string if you wanted to put any variables that are read out in there as well so now we've got the body of this we're going to make an object that starts capturing all of the different parts of this kind of email package so I'm going to call that MSG and uh start stringing this together there we go so we have created the object here and we're just assigning parts of this object our different variable names so where the email is coming from the person which is the current iteration through that list and the subject which we made up here and now we've done that we want to attach um attach the the body so what we made here we want to attach this to that same object message okay so what we've done there is just said message.attach uh we're calling this um this mind text function from the library we've uh we we've imported and this body is this guy here the texture that is actually in the in the body of the email and we're just saying that this is plain text so that's what that little string is there so that's the the guts of the the email itself let's have a look at how we actually attach a file so in this uh in this folder here I've got a CSV called random data have a look in there it is just a table of just random data I put together I'm in Excel but this is uh this is actually a CSV file so how do we attach that to the email so I'm just going to do this as a straight straight up hard code of the name but what I generally do for my uh for my things that I built I have the data logged and time stamped well the name is the timestamp and that can be fed into well you just put it as another as another argument in this function that whatever the timestamp of that CSV is that's what you are pulling in and making this uh making this message name equal to so that's the name of the thing as a string and obviously don't forget your dot CSV or dot whatever your file is at the end of that so now we know what file we're looking for we're going to open this file as a I'll open it to read that as a binary there we go so I've just created this variable called attachment and that is basically opening whatever the file is and I've used the this string here r b uh R is for reading the file and B is for doing that as a binary so that is what attachment then becomes so once we've done that we now to now need to encode it um encode it in base64 so let's have a go at that Okay so well you can kind of see it yourself it's a bit convoluted but we're making a variable called attachment passage and package um which is uh this mind-based object and we're just loading in the different bits and Bobs we're telling it to set the payload as the attachment itself which is this binary file we've just opened and then we're encoding it adding some headers um while the actual file name is blah blah blah blah and then lastly we're attaching that to this uh this MSG object that we were we were making before what we're going to do now is just cast it to a string I'm just going to call text there we go and this uh this is the thing that will actually be firing into the the email now we've now we've cast it to that string so now we've got all that set up the um the playthrough is pretty similar to the last one where we just start up connections with the server and then fire off this email do remember however we are in this Loop so we need to do it a bit different just to iterate through each of those emails that we have in that list so let's uh let's connect with that server now all right so this should connect us with the server quite nicely so again we're just printing stuff out for the user just so they know where they are in the program um we're making uh again an object called tie server same as the last one so the actual SMTP server and the port as arguments we're starting up that TLS of that server and then we're logging in using our email and our password if that all works and we let the user know that we've connected to that server so once we're connected we actually do the same thing we we send we send this email there we go so again don't forget where we are in this uh looping list here so we're going to iterate through and it's just tie server.send mail and then who's the email from the person which is the iteration through that email list uh in this case it's just me three times and then the text which is what we uh we cast the entire message to including all the base64 encoding stuff and as always just letting the user know what's going on so once we've done all that and once the list is completed so backspace one are those tabs we're going to make sure that we we quit that server so and there we go that is uh that is the entire function so if uh we just call this function at the bottom remember we need to put in the email list as an argument okay so let's pull up our command line and see if uh see if this works again I don't know if you can hear my phone buzzing but that sounded like it worked let's have a look in our emails here we go three emails from me you can see now we have a subject line in here we can see we have our nice line breaks line one line two line three Etc and we've got our CSV nicely attached so that's all well and good come out of this all we want to do now is well obviously for the purposes of this YouTube video I want to get rid of that password but the process is exactly the same so we come up here to our little icon click him and manage our Google account exactly the same as last time into security let me come down here and now we can see we have app passwords one password click on that to go into it re-enter our password and here we go so SMTP email so this is the one we made earlier and we're going to bend this off good so now that is gone forever even if I made a new one it would be a completely different uh keep completely different key and still wouldn't work with the code that we have written here that will be on GitHub and just to show you that if I try and run this code again we're going to get um we're going to get this username and password not accepted so we know that that deactivation has worked so as always the link to the GitHub where all this code will be is in the description below so I'll be free to download it have a play around with it put it into your own projects if you have any questions again pop it in the comments let me know and I will see you guys in the next video [Music]
Info
Channel: The Intrigued Engineer
Views: 28,580
Rating: undefined out of 5
Keywords: python, pi, computer, email, automatic, code, SMTP, smtp, MIME, SSL
Id: Sddnn6dpqk0
Channel Id: undefined
Length: 22min 27sec (1347 seconds)
Published: Sat Oct 22 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.