You may come across the situation, where you want to send a certain message to different contacts. Maybe you also need to slightly change the message for each receiver. In this video, you’ll learn how to use CSV files to do exactly that! In this case you are a teacher, who wants to inform his students about their grades.
Sending Multiple Emails From a CSV File
In this video, you’ll learn to use a CSV file as an input so that you can fire off a bunch of emails with one script. Over here, I’ve got a
contacts.csv file that has the name, email, and grade for a couple of fake people.
Note the email addresses where I’ve added a plus (
+), and then the person’s name to my test email. When Gmail’s routing the email, it’s going to ignore anything after the
+ sign, so all of these will be sent to my test email but kept separate.
Okay. Much of this will be the same. You’ll create a
ssl, create a default context. Let me bring this down. Okay. With
smtplib.SMTP_SSL()—and because we’re not really messing around with these anymore, I’m just going to type them in as strings instead of setting variables for them.
And then unpack that as
for name, email, grade in reader: you’re going to
.sendmail(). You need to pass in your
message, which is from the message template above.
04:11 Okay! So if this works the way it should, it’ll log into the server like we’ve done before, and then it’s going to go through your CSV file and then for each row in there, it’s going to send an email based on the information that’s in that CSV.
04:36 We don’t see any errors, so let’s hop over. And what do we have here? Okay. So Your Grades, it looks like here’s one for Ron, here’s one for Rabbit, and you can see that the template has been changed for each of them. So this was sent to Ron, and Rabbit, and I think I got one more here. Yeah, there’s the third one there. All right!
04:59 So now you can see that with one script and a CSV file, you can send out multiple emails that are personalized. That’s pretty cool. You can use this kind of system if you need to verify somebody’s email for a website or if you’re running an email list with Python.
Become a Member to join the conversation.