I am taking a python course from udemy. I have a hard time doing the homework of the Smtp module. The homework's explanation is "Write a file with the e-mails and names of 5 people. Try to read this file and send an e-mail to each person with their name. The file format will be as follows.
name,email
//
//
//
//
"
I've make progress at homework. The part that I cannot do in the homework is to change and send the message according to the person's name.
Here is the code:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import sys
clean_lines_list = list()
names = list()
adresses = list()
with open("names_and_adresses.txt","r+",encoding="utf-8") as file:
lines = file.readlines()
for line in lines:
clean_lines = line.strip("
")
clean_lines_list.append(clean_lines)
names.append(clean_lines.split(",")[0])
adresses.append(clean_lines.split(",")[1])
message = MIMEMultipart()
recipients_list = adresses
_from_ = "[email protected]"
message["From"] = _from_
message["To"] = ", ".join(recipients_list)
message["Subject"] = "Sending Email With Python"
text = """
I'm sending an email with Python.
"""
message_body = MIMEText(text,"plain")
message.attach(message_body)
try:
mail = smtplib.SMTP("smtp.gmail.com",587)
mail.ehlo()
mail.starttls()
mail.login("[email protected]","password")
mail.sendmail(_from_,recipients_list,message.as_string())
print("Mail Sucessfully Sent")
mail.close()
except:
sys.stderr.write("An Error Ocurred")
sys.stderr.flush()
With this code, I can send email to the people with same message.
question from:
https://stackoverflow.com/questions/65952720/how-can-i-send-emails-to-people-with-their-names-which-are-in-a-file 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…