使用不同的问候语向多个用户发送电子邮件?

时间:2017-08-07 18:33:25

标签: python email

我正在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 = 'emailexample@gmail.com'

smtp_user = 'emailexample@gmail.com'
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()

1 个答案:

答案 0 :(得分:0)

您必须为每个收件人重建SMTP发送的邮件和邮件。这是应该工作的:

recipients = emailRecipients
addr_from = 'emailexample@gmail.com'

smtp_user = 'emailexample@gmail.com'
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()