0

Noob,创建了他的第一个动态网页,用户可以在其中输入消息,以及他们的名字和姓氏、电子邮件和电话号码。我最关心我打算通过电子邮件转发的消息以及其他信息(如果提供)。我编写了一个简单的 python 脚本(站点将是 Flask、python 和 HTML),但它在每个输出之间插入了一条不需要的水平线,即

亲爱的鲍勃


留言内容到这里



我的目标是让传出消息类似于实际的电子邮件,即如上所示,但没有水平线。我在网上找到了以下大部分代码,这在很大程度上是有效的。我能理解的简单答案优于我不能理解的聪明答案(我是菜鸟)。

def to_mail(first, last, phone, email, User_Complaint, addressed_to):
    # E mail account details
    my_sending_email = 'testing@gmail.com'
    sending_email_password = 'pass'

    # set up the SMTP server
    s = smtplib.SMTP(host='smtp.gmail.com', port=587)
    s.starttls()
    s.login(my_sending_email, sending_email_password)

    msg = MIMEMultipart()

    msg['Subject'] = 'Reporting an Issue With the Courts'
    msg['From'] = my_sending_email
    msg['To'] = addressed_to

    # Body of Email
    intro = MIMEText("Dear Leader")
    message_contents = MIMEText(User_Complaint)

    # use of .attach appears to insert the horizontal line
    msg.attach(intro)
    msg.attach(message_contents)

    # Party's Contact Info to append at bottom of email
    msg.attach(MIMEText(first + last))
    msg.attach(MIMEText(phone))
    msg.attach(MIMEText(email))

    s.send_message(msg)
    del msg

    s.quit()

我只想在邮件正文中生成正常外观的电子邮件内容,即

“尊敬的领导,

我真的很喜欢你的头发。我是你最忠实的粉丝。

(后面的每个传记条目都应该在自己的换行符上,但这会自动将其放在一行上)Stan Lee\n stan@lee.com\n 647-647-1234"

4

2 回答 2

1

感谢 Assili,我能够根据您的建议通过以下小调整来修复我的代码。

#Body of Email

text = intro + '\n' + '\n'  + message_contents + '\n' + '\n' + first + '' + last + '\n' + phone + '\n' + email 

msg.attach(MIMEText(text))
于 2019-05-29T14:45:23.980 回答
1

您需要使用单个 msg.attach 来避免多条水平线:

# Body of Email
text = "Dear Leader\n" + User_Complaint + "\n" + phone + "\n" + email
html = """\
<html>
  <head></head>
  <body>
    <p>Dear Leader<br>
       I really like your hair. I'm your biggest fan.<br>
       (each biographic entry following should be on 
its own newline, but this automatically puts it on one line)
Stan Lee\n stan@lee.com\n 647-647-1234.
    </p>
  </body>
</html>
"""

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

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

s.send_message(msg)
del msg
s.quit()

最好在 html 和 txt 文件中定义邮件正文并使用 jinja2 模板引擎呈现这些文件。所以你需要创建两个文件:

邮件文本

Dear Bob!\n
{{ User_Complaint }}\n
{{ phone }} \n
{{ email }}

邮件.html

<html>
  <head></head>
  <body>
    <p>
    Dear Bob!<br/>
    {{ User_Complaint }}<br/>
    {{ phone }}<br/>
    {{ email }}
   </p>
  </body>
</html>

而 to_mail 函数将与此类似:

from flask import render_template
def to_mail(first, last, phone, email, User_Complaint, addressed_to):

    # The old code
    #...
    # Body of Email
    part1 = render_template("mail.txt",
    User_Complaint = User_Complaint,
    email=email, phone=phone)

    part2 = render_template("mail.html",
    User_Complaint = User_Complaint,
    email=email, phone=phone)

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

    s.send_message(msg)
    del msg
    s.quit()

使用flask-mail发送邮件也不错。

于 2019-05-29T01:48:35.617 回答