2009-12-23 3 views
1

파이썬에서 results.txt 파일의 마지막 15 줄을 이메일로 보낼 전자 메일 기능을 설정하려고합니다. 어떻게 해야할지 모르겠다. 이메일 서버에 연결해야하는지 아니면 파이썬에 이메일을 보내는 다른 방법이 있는지 묻고 있었다. 아래의 코드는 내가 지금까지 가지고있는 것이고 어떤 도움을 주시면 감사하겠습니다. 감사합니다파이썬 텍스트 파일의 마지막 줄을 전자 메일로 보내기

import smtplib 

# Import the email modules we'll need 
from email.mime.text import MIMEText 

# Open a plain text file for reading. For this example, assume that 
# the text file contains only ASCII characters. 
fp = open('/home/build/result.txt', 'r') 
# Create a text/plain message 
msg = MIMEText(fp.read()) 
fp.close() 

me = '[email protected]' 
you = '[email protected]' 
msg['Subject'] = 'The contents of %s' % '/home/build/result.txt' 
msg['From'] = me 
msg['To'] = you 

# Send the message via our own SMTP server, but don't include the 
# envelope header. 
s = smtplib.SMTP() 
s.sendmail(me, [you], msg.as_string()) 
s.quit() 

안녕하세요 다시

I 서버가 연결되지 않습니다 연결을 시도하고있다. 이메일 주소를 입력해서는 안된다는 것을 알고 있습니다. 누구든지 호스트 정보를 작성하는 방법을 제안 할 수 있습니까? 감사합니다

smtplib.SMTPServerDisconnected: please run connect() first 

답변

4

컴퓨터를 사용할 방법이 없습니다. 서버에 연결하지 않고 메일을 보내십시오 (그렇지 않으면 메일이 컴퓨터에서 어떻게 빠져 나옵니까?). 대부분의 사람들은 회사 (인트라넷에있는 경우) 또는 ISP (가정 사용자 인 경우)를 통해 쉽게 사용할 수있는 SMTP 서버를 제공합니다. 호스트 이름 (보통 smtp1.myispdomain.com과 같이 myispdomain이 다른 것)과 포트 번호 (보통 25)가 필요합니다. 때때로 호스트는 192.168.0.1과 같은 숫자 IP 주소로 제공됩니다.

SMTP() 호출은 이러한 매개 변수를 사용할 수 있으며 자동으로 서버에 연결합니다. SMTP 개체를 만들 때 매개 변수를 제공하지 않으면 나중에 동일한 정보를 제공하여 connect()에 전화해야합니다. 자세한 내용은 documentation을 참조하십시오.

기본값은 localhost 및 포트 25에 연결하는 것입니다. 이것은 자신의 메일 전달자 (예 : Postfix, Sendmail, Exim)를 실행중인 Linux 상자에 있지만 Windows 컴퓨터에있는 경우 ISP가 제공 한 주소를 사용해야합니다.

1
msg = MIMEText("\n".join(fp.read().split("\n")[-15:])) 

아니면 끝 부분에 빈 줄 필요하지 않은 경우

msg = MIMEText("\n".join(fp.read().strip().split("\n")[-15:])) 
2
msg = MIMEText(''.join(fp.readlines()[-15:])) 
0

mailer 모듈을 살펴볼 수 있습니다. 전자 메일 모듈을 표준 라이브러리에 래핑합니다.

from mailer import Mailer 
from mailer import Message 

message = Message(From="[email protected]", 
        To="[email protected]", 
        charset="utf-8") 
message.Subject = 'The contents of %s' % '/home/build/result.txt' 
message.Body = ''.join(fp.readlines()[-15:]) 

sender = Mailer('smtp.example.com') 
sender.login('username', 'password') 
sender.send(message) 
관련 문제