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
255 views
in Technique[技术] by (71.8m points)

Python email - can only sendmail to one address

My SendMail function looks like this:

MY_SMTP = #I can't show it here

def SendMail(authentication_data, email_from, email_to_list, email_cc_list, email_subject, email_message, list_file)
    user_name = authentication_data["name"]
    user_password = authentication_data["password"]
    msg = MIMEMultipart(email_message)
    server = smtplib.SMTP(MY_SMTP)
    server.starttls()
    emails_list_string = ", ".join(email_to_list)
    emails_cc_list_string = ", ".join(email_cc_list)

    msg["From"] = email_from
    msg["To"] = emails_list_string
    msg["Cc"] = emails_cc_list_string
    msg["Subject"] = "TEST"
    msg["Date"] = email.Utils.formatdate()

    msg.attach(MIMEText(email_message))

    server.login(user_name, user_password)
    server.sendmail(email_from, emails_list_string + ", " + emails_cc_list_string, msg.as_string())

    server.quit()

When I use this function and I pass a list of e-mail addresses for email_to_list, it only sends an e-mail to the first element of the list. Passing any list for email_cc_list simply adds addresses to the Cc field in the e-mail, however I think it's purely cosmetic, as the people in the Cc don't see the e-mail when I send it with this function. Basically only the first address in email_to_list ever receives the e-mail.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The documentation says:

The required arguments are an RFC 822 from-address string, a list of RFC 822 to-address strings (a bare string will be treated as a list with 1 address), and a message string.

When you pass emails_list_string + ", " + emails_cc_list_string to server.sendmail as the second parameter, it treats it as a single address, probably chopping off everything after the first comma. Try like this instead:

server.sendmail(email_from, email_to_list + email_cc_list, msg.as_string())

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

...