使用Python的HTML格式电子邮件

2024-04-25 22:42:26 发布

您现在位置:Python中文网/ 问答频道 /正文

免责声明:初学者

嗨,我正在尝试建立一个格式化的电子邮件发件人。我希望它能够发送电子邮件到一个用户输入的电子邮件列表,并将其格式化为一个名单的名字,以便它发送每个电子邮件格式化。有人知道怎么做吗?你知道吗

我也希望它没有格式,其中没有名字在名单上。因此,当列表中没有名字时,电子邮件将显示为“嗨!等等。”

目前,它将格式化名字,但只会发送一封电子邮件,并将格式从列表中的任何其他名称到一封电子邮件(出来像“嗨本,戴夫”)。你知道吗

我有另一个模型,我正在工作,使用.csv文件,在任何人提出这种方法之前,但我想有一个模型使用输入列表,如果没有别的,但看看如何,如果它将工作。你知道吗

还有python codex的功劳,功劳到期的功劳。你知道吗

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage


host = "smtp.gmail.com"
port = 587
username = "xxx@gmail.com"
password = "xxx"
from_email = username
to_list = input('Please enter emails seperated by a comma: ')
Name_list = input('Please enter names seperated by a comma: ')
email_conn = smtplib.SMTP(host, port)
email_conn.ehlo()
email_conn.starttls()
email_conn.login(username, password)


the_msg = MIMEMultipart('alternative')
the_msg['Subject'] = "Link"
the_msg["From"] = "xxx@gmail.com"
the_msg["To"] = to_list

plain_txt = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html_txt = """\
<html>
  <head></head>
  <body>
    <p>Hi {name}!<br>
       How are you?<br>
       Here is the <a href="http://www.python.org">link</a> you wanted.<br>
       <img src="cid:image1">
    </p>
  </body>
</html>
""".format(name=Name_list)


fp = open('/Users/xxx/xxx.png', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()


msgImage.add_header('Content-ID', '<image1>')
the_msg.attach(msgImage)


part_1 = MIMEText(plain_txt, 'plain')
part_2 = MIMEText(html_txt, "html")
the_msg.attach(part_1)
the_msg.attach(part_2)


print(the_msg.as_string())


from smtplib import SMTP, SMTPAuthenticationError, SMTPException

pass_wrong = SMTP(host, port)
pass_wrong.ehlo()
pass_wrong.starttls()
try:
    pass_wrong.login(username, "wrong_password")
    pass_wrong.sendmail(from_email, to_list, "")
except SMTPAuthenticationError:
    print("Message sent")
except:
    print("an error occured")

pass_wrong.quit()

email_conn.sendmail(from_email, to_list, the_msg.as_string())
email_conn.quit()

Tags: thefromimport列表电子邮件emailhtmlusername

热门问题