2017-08-07 48 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() 
相关问题