# Web scraping
import urllib
import smtplib
from urllib.request import urlopen
from bs4 import BeautifulSoup
def make_soup(url):
thePage= urllib.request.urlopen(url)
soupdata = BeautifulSoup(thePage, "html.parser")
return soupdata
soup = make_soup("http://www.met.gov.kw/?lang=eng")
for record in soup.select('#newForecast'):
information = record.text
content = information[48:440]
msg = content
以下是代码的一部分我遇到问题时,我将内容中存储的信息传输到邮件,然后将其传递给sendmail()函数,其中正文邮件应该显示为空 你能告诉我出了什么问题吗?
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login("yourEmail", "yourPassword")
server.sendmail("placeholder", "placeholder", msg)
server.quit()
答案 0 :(得分:1)
您的变量msg
是原始内容字符串。对于电子邮件内容,您必须使用MIME类型(Multipurpose Internet Mail Extensions)。
在Python中,您可以使用对象MIMEText
(仅用于文本)或MIMEMultipart
(带附件)。它会使用函数as_string()
将您的内容转换为等效的MIME格式。
或者您可以使用MIME格式构建自己的String。 ;)
这是我对您的代码的更正。这应该有效:
# import the object MIMEText
from email.mime.text import MIMEText
...
# build a instance of MIMEText from your content string
msg = MIMEText(content)
# Subject, From, To are the information, which the receiver will see
# It's no problem, if you use a fake address here. That's the way, how phishing mail or spam mail works
msg['Subject'] = 'Subject of my email'
msg['From'] = "placeholder"
msg['To'] = "placeholder"
...
# now use as_string() to convert your data to equivalent MIME format
# you can use `print msg.as_string()` to see how it is.
server.sendmail("placeholder", "placeholder", msg.as_string())
更多示例email examples