Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
102 views
in Technique[技术] by (71.8m points)

python - How can I send emails to people with their names which are in a file?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...