clattenburg cake
clattenburg cake

Reputation: 1222

Mass Email Via Python, Custom Body

New to Python, I'm trying to write a mass-email script (it will be sent via gmail).

Basically I have got it working, however I need to edit each message body separately with a greeting to name of the e-mail recipient. Currently the body is read off a body.txt file and I am not sure how to edit it. Example:

body.txt

Hi <recipient>,

Here is your voucher code.

And this is my script, send_email.py:

import smtplib
from email.mime.text import MIMEText

from_address = "[email protected]"
file = open("body.txt","rb")
message = MIMEText(file.read())
file.close()
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(from_address, "XXXXX")
server.set_debuglevel(1)
sender = from_address
recipients = ['[email protected]', '[email protected]']
message['Subject'] = "Voucher Code"
message['From'] = sender
message['To'] = ", ".join(recipients)
server.sendmail(sender, recipients, message.as_string())

I think most probably I will have to create another list with the names of recipients and match them to the email addresses to be sent to, but I'm not sure how to go from there. In fact, I'm not even sure this is the best way- it works though, so I'm pretty happy so far, apart from not being able to edit the body. How do I go from here?

Upvotes: 0

Views: 225

Answers (1)

Povilas Kirna
Povilas Kirna

Reputation: 84

I've seen what you did and I think it's a great start. To edit in the recipients name to the message is really quite simple. You need to format the string. Here's an example:

emailBody = "Hello {}, this is my email body. As you can see this program inserts every recipient separately. Hopefully it is helpful. \n"
recipients = ["Ann", "Josh", "Bob", "Marie"]
for recipient in recipients:
    print(emailBody.format(recipient))

The main thing is that your emailBody must include symbols {} and then you can use

emailBody.format(content)

to put something into those brackets.

Upvotes: 1

Related Questions