2017-08-07 73 views
-3

我正在python中創建一個電子郵件腳本。我可以將郵件發送給多個用戶,但我希望它能夠說出「Hello Jordan」或收件人在郵件正文之前的名稱。如果有幫助,我可以顯示我的代碼。發送電子郵件給不同問候的多個用戶?

import smtplib 

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

from email_R import emailRecipients 

recipients = emailRecipients 
addr_from = '[email protected]' 

smtp_user = '[email protected]' 
smtp_pass = 'password' 

try: 
    msg = MIMEMultipart('alternative') 
    msg['To'] = ", ".join(recipients) 
    msg['From'] = addr_from 
    msg['Subject'] = 'Test Email' 

    text = "This is a hours reminder.\nText and html." 
    html = """\ 
    <html> 
     <head></head> 
     <body> 
      <p>This is a hours reminder.</p> 
      <p>Text and HTML</p> 
     <body> 
    </html> 
    """ 

    part1 = MIMEText(text, 'plain') 
    part2 = MIMEText(html, 'html') 

    msg.attach(part1) 
    msg.attach(part2) 

    server = smtplib.SMTP('smtp.gmail.com:587') 
    server.set_debuglevel(True) 
    server.starttls() 
    server.login(smtp_user,smtp_pass) 
    server.sendmail(msg['From'], recipients, msg.as_string()) 
    server.quit() 
+3

不僅它的幫助,它是強制性的 – Kai

+0

「之前」的身體是不可能的。您需要自定義每個「主題」標題​​或自定義每個收件人的主體。這不是嚴格的Python問題,但是這涉及RFC822和SMTP傳輸規則。 – glenfant

+1

請查看SO [如何詢問[(https://stackoverflow.com/questions/ask/advice?),其中包括提供一組可用於重現問題的代碼。所以是的,請提供您的代碼。 –

回答

0

您必須重建每個收件人的SMTP發送郵件和湖。這是什麼應該工作:

recipients = emailRecipients 
addr_from = '[email protected]' 

smtp_user = '[email protected]' 
smtp_pass = 'password' 

server = smtplib.SMTP('smtp.gmail.com:587') 

try: 
    subject_tpl = 'Test Email for {}' 
    text_tpl = "This is a hours reminder for {}.\nText and html." 
    html_tpl = """\ 
    <html> 
     <head></head> 
     <body> 
      <p>This is a hours reminder for {}.</p> 
      <p>Text and HTML</p> 
     <body> 
    </html> 
    """ 
    server.set_debuglevel(True) 
    server.starttls() 
    server.login(smtp_user,smtp_pass) 

    # Loop for each recipient 
    for recipient in recipients: 
     msg = MIMEMultipart('alternative') 
     msg['Subject'] = subject_tpl.format(recipient) 
     msg['To'] = recipient 
     msg['From'] = addr_from 
     part1 = MIMEText(text_tpl.format(recipient), 'plain') 
     part2 = MIMEText(html_tpl.format(recipient), 'html') 
     msg.attach(part1) 
     msg.attach(part2) 
     server.sendmail(msg['From'], (recipient,), msg.as_string()) 
finally: 
    server.quit() 
相關問題