2013-01-25 66 views
1

下面的代碼是從ESPN/college-football中提取頭條新聞。我可以抓住文章的標題和鏈接。我可以打印這兩個,但我也想給他們發電子郵件。我可以獲得電子郵件的標題,但不能獲得href屬性。任何想法發生了什麼?Python:試圖發送電子郵件href

from urllib import urlopen 
from BeautifulSoup import BeautifulSoup 
import smtplib 

# Copy all of the content from the provided web page 
webpage = urlopen('http://espn.go.com/college-football').read() 
soup = BeautifulSoup(webpage)  

# to get the contents of <ul> tags w/ attribute class="headlines": 
for i in soup.findAll('ul', {'class': 'headlines'}): 
    for tag in i.findAll('li'): 
     for a in tag.findAll({'a' : True, 'title' : False}):    
      print a.text 
      print a['href']         
      print "\n" 

      url = str(a.get('href')) 
      fromaddr = '[email protected]' 
      toaddrs = '[email protected]'    


      # Credentials (if needed) 
      username = 'username' 
      password = 'password' 

      # The actual mail send 
      server = smtplib.SMTP('smtp.gmail.com', 587) 
      server.set_debuglevel(1) 
      server.ehlo() 
      server.starttls() 
      server.login(username,password) 
      server.sendmail(fromaddr, toaddrs, url) 
      server.quit() 

Eclipse中的控制檯顯示:

reply: '235 2.7.0 Accepted\r\n' 
reply: retcode (235); Msg: 2.7.0 Accepted 
send: 'mail FROM:<person> size=106\r\n' 
reply: '250 2.1.0 OK a9sm22683966anb.6\r\n' 
reply: retcode (250); Msg: 2.1.0 OK a9sm22683966anb.6 
send: 'rcpt TO:<emailHere>\r\n' 
reply: '250 2.1.5 OK a9sm22683966anb.6\r\n' 
reply: retcode (250); Msg: 2.1.5 OK a9sm22683966anb.6 
send: 'data\r\n' 
reply: '354 Go ahead a9sm22683966anb.6\r\n' 
reply: retcode (354); Msg: Go ahead a9sm22683966anb.6 
data: (354, 'Go ahead a9sm22683966anb.6') 
send: 'http://espn.go.com/college-sports/story/_/id/8878732/lawyer-ncaa-miami- hurricanes-investigation-says-patsy\r\n.\r\n' 
reply: '250 2.0.0 OK 1359087354 a9sm22683966anb.6\r\n' 
reply: retcode (250); Msg: 2.0.0 OK 1359087354 a9sm22683966anb.6 
data: (250, '2.0.0 OK 1359087354 a9sm22683966anb.6') 
send: 'quit\r\n' 
reply: '221 2.0.0 closing connection a9sm22683966anb.6\r\n' 
reply: retcode (221); Msg: 2.0.0 closing connection a9sm22683966anb.6 

,但它從來沒有遇到的電子郵件。

回答

1

嘗試email封裝格式電子郵件:

# -*- coding: utf-8 -*- 
from email.header import Header 
from email.mime.text import MIMEText 

msg = MIMEText('put message body here…', 'plain', 'utf-8') 
msg['Subject'] = Header('here goes subject…', 'utf-8') 
msg['From'] = '[email protected]' 
msg['To'] = '[email protected]' 
print(msg.as_string()) 

輸出:

 
Content-Type: text/plain; charset="utf-8" 
MIME-Version: 1.0 
Content-Transfer-Encoding: base64 
Subject: =?utf-8?q?here_goes_subject=E2=80=A6?= 
From: [email protected] 
To: [email protected] 

cHV0IG1lc3NhZ2UgYm9keSBoZXJl4oCm 

要通過Gmail發送:

from smtplib import SMTP_SSL 

s = SMTP_SSL('smtp.gmail.com') 
s.set_debuglevel(1) 
try: 
    s.login(login, password) 
    s.sendmail(msg['From'], msg['To'], msg.as_string()) 
finally: 
    s.quit() 
+0

工作就像一個魅力。謝謝J.F! –