【问题标题】:Python sending blank e-mails [duplicate]Python发送空白电子邮件[重复]
【发布时间】:2014-11-12 00:00:17
【问题描述】:

我已经写了这段代码

import urllib.request
import smtplib
import re

htmlweb = urllib.request.urlopen('url goes here')

htmltext = htmlweb.read().decode('utf-8')

regex = '<h2 itemprop="name">(.+?)</h2>'

regex2 = '<div class="mediaPageName">(.+?)</div>'

pattern = re.compile(regex)

pattern2 = re.compile(regex2)

username = re.findall(pattern, htmltext)

interests = re.findall(pattern2, htmltext)

content = "The person's name is: "

i=0
ii=0

while i<len(username):
    content += username[i]
    i += 1

content += "\nTheir interests are: "

while ii<len(interests):
    content += interests[ii] + ", "
    ii += 1

#-----------------------------------------------

mail = smtplib.SMTP("smtp.gmail.com", 587)

mail.ehlo()

mail.starttls()

mail.login('email here', 'password here')

mail.sendmail('email here', 'here too', content)

mail.close()

但是,当我运行它时,我会收到一封没有正文的电子邮件。 content 变量将我想要的内容打印到控制台,而不是电子邮件正文。

对不起,如果这是微不足道的;这是我第一次尝试 Python。

谢谢!

【问题讨论】:

  • 我去看看这两篇文章。
  • @Sam,仅供参考,以供将来使用 SO,如果您认为一切正常,但不是,请尽可能多地分享。在这种情况下,您提供了很棒的代码,但没有分享 content 的内容,这可能有助于更快地指出您的问题

标签: python list email


【解决方案1】:

以下问题:smtplib sends blank message if the message contain certain characters,指出您必须以新行开始邮件内容,否则内容将成为邮件标题而不是邮件正文的一部分。

我相信你必须改变:

content = "The person's name is: "

到这里:

content = "\nThe person's name is: "

【讨论】:

  • 做到了!非常感谢您的帮助。挑剔的东西,不是吗?
  • 是的,这些问题会让您头疼好几个小时。