0

Hi I been trying to send an email with python but errors keep popping up. This is my script.

import smtplib

from string import Template

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

MY_ADDRESS = '*****@gmail.com'
PASSWORD = '*****'


def get_contacts(filename):
    """
    Return two lists names, emails containing names and email addresses
    read from a file specified by filename.
    """

names = []
emails = []
with open(filename, mode='r', encoding='utf-8') as contacts_file:
    for a_contact in contacts_file:
        names.append(a_contact.split()[0])
        emails.append(a_contact.split()[1])
return names, emails


def read_template(filename):
    """
    Returns a Template object comprising the contents of the
    file specified by filename.
    """

with open(filename, 'r', encoding='utf-8') as template_file:
    template_file_content = template_file.read()
return Template(template_file_content)


def main():
    names, emails = get_contacts('mycontacts.txt')  # read contacts
    message_template = read_template('message.txt')

# set up the SMTP server
s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
s.login(MY_ADDRESS, PASSWORD)


# For each contact, send the email:
for name, email in zip(names, emails):
    msg = MIMEMultipart()  # create a message

    # add in the actual person name to the message template
    message = message_template.substitute(PERSON_NAME=name.title())

    # Prints out the message body for our sake
    print(message)

    # setup the parameters of the message
    msg['From'] = MY_ADDRESS
    msg['To'] = email
    msg['Subject'] = "This is TEST"

    # add in the message body
    msg.attach(MIMEText(message, 'plain'))

    # send the message via the server set up earlier.
    s.send_message(msg)
    del msg

# Terminate the SMTP session and close the connection
s.quit()


if __name__ == '__main__':
    main()

Traceback (most recent call last):
  File "C:/Users/tyger_000/Desktop/Object Oriented Programming/Project/Private-Group-Work-OOPP/SmartLifestyle(Combined)/Email Sender/email_sender.py", line 75, in <module>
    main()
  File "C:/Users/tyger_000/Desktop/Object Oriented Programming/Project/Private-Group-Work-OOPP/SmartLifestyle(Combined)/Email Sender/email_sender.py", line 53, in main
    message = message_template.substitute(PERSON_NAME=name.title())
  File "C:\Program Files\Python35\lib\string.py", line 125, in substitute
    return self.pattern.sub(convert, self.template)
  File "C:\Program Files\Python35\lib\string.py", line 122, in convert
    self._invalid(mo)
  File "C:\Program Files\Python35\lib\string.py", line 95, in _invalid
    (lineno, colno))
ValueError: Invalid placeholder in string: line 1, col 17

This is the mycontacts.txt file

user@computer ~ $ cat mycontacts.txt
john john@gmail.com

and this is my message.txt

user@computer ~ $ cat message.txt
Dear ${PERSON_NAME},

Brace Yourselves,
Haze is coming!

Yours Truly

I do not know what is wrong and I am a new user. Please help. Thank yo. The error at first was the targeted machine refusing but after solving that, this happened. Do I need to install a email package or something similar and if so how do I do it?

Seong
  • 1
  • 1
  • 2

3 Answers3

1

Take out the $ symbol from the tempate

 Dear {PERSON_NAME},

or maybe if the module is newer use double curly braces {{}}:

 Dear {{PERSON_NAME}},
johnashu
  • 2,167
  • 4
  • 19
  • 44
0

Take out the $ symbol from the tempate

 Dear {PERSON_NAME},
johnashu
  • 2,167
  • 4
  • 19
  • 44
  • You have posted an additional answer which also covers this aproach. Please delete this one (or maybe the other one....), in order to not have unneeded content cluttering the page. – Yunnosch Apr 23 '23 at 14:06
0

Nothing is wrong in your script nor in your txt files, it is running fine on my system!! Please try to run again in the different file or in other systems. Or there may be some problem with your python lib files.

You don't need to remove $ from your txt file like answered by @johnashu

Jai Singhal
  • 410
  • 5
  • 9