파이썬에서 sendmail을 통해 메일 보내기
SMTP가 아닌 sendmail을 통해 메일을 보내려면이 프로세스를 캡슐화하는 Python 용 라이브러리가 있습니까?
더 좋은 점은 전체 'sendmail -versus- smtp'선택을 추상화하는 좋은 라이브러리가 있습니까?
이 스크립트를 여러 유닉스 호스트에서 실행할 것이며 그중 일부만 localhost : 25에서 수신 대기하고 있습니다. 이들 중 일부는 임베디드 시스템의 일부이며 SMTP를 허용하도록 설정할 수 없습니다.
Good Practice의 일환으로 라이브러리가 헤더 주입 취약점 자체를 처리하도록 popen('/usr/bin/sendmail', 'w')하고 싶습니다. 따라서 문자열을 덤핑하는 것만으로도 내가 원하는 것보다 금속에 조금 더 가깝습니다.
대답이 '라이브러리를 써라'라면, 그러니 ;-)
헤더 삽입은 메일을 보내는 방법의 요소가 아니라 메일을 구성하는 방법의 요소입니다. 이메일 패키지를 확인하고 , 그로 메일을 구성하고, 직렬화하고, 하위 프로세스 모듈 을 /usr/sbin/sendmail사용하여 전송합니다 .
from email.mime.text import MIMEText
from subprocess import Popen, PIPE
msg = MIMEText("Here is the body of my message")
msg["From"] = "me@example.com"
msg["To"] = "you@example.com"
msg["Subject"] = "This is the subject."
p = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE)
p.communicate(msg.as_string())
이것은 메일을 전달하기 위해 유닉스 sendmail을 사용하는 간단한 파이썬 함수입니다.
def sendMail():
sendmail_location = "/usr/sbin/sendmail" # sendmail location
p = os.popen("%s -t" % sendmail_location, "w")
p.write("From: %s\n" % "from@somewhere.com")
p.write("To: %s\n" % "to@somewhereelse.com")
p.write("Subject: thesubject\n")
p.write("\n") # blank line separating headers from body
p.write("body of the mail")
status = p.close()
if status != 0:
print "Sendmail exit status", status
Jim의 대답은 Python 3.4에서 나를 위해 작동하지 않았습니다. 추가 universal_newlines=True인수를 추가 해야했습니다.subrocess.Popen()
from email.mime.text import MIMEText
from subprocess import Popen, PIPE
msg = MIMEText("Here is the body of my message")
msg["From"] = "me@example.com"
msg["To"] = "you@example.com"
msg["Subject"] = "This is the subject."
p = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE, universal_newlines=True)
p.communicate(msg.as_string())
universal_newlines=True나는 얻지 않고
TypeError: 'str' does not support the buffer interface
os.popen을 사용하여 Python에서 sendmail 명령을 사용하는 것은 매우 일반적입니다.
개인적으로 내가 직접 작성하지 않은 스크립트의 경우 SMTP 프로토콜을 사용하는 것이 더 낫다고 생각합니다. 창에서 실행하기 위해 sendmail 클론을 설치할 필요가 없기 때문입니다.
https://docs.python.org/library/smtplib.html
이 질문은 매우 오래되었지만 이 메시지가 요청되기 전부터 사용 가능한 Marrow Mailer (이전 TurboMail) 라는 메시지 구성 및 전자 메일 전달 시스템이 있다는 점에 유의할 가치 가 있습니다.
이제 Python 3을 지원하도록 이식되고 Marrow 제품군의 일부로 업데이트되었습니다 .
나는 똑같은 것을 찾고 있었고 Python 웹 사이트에서 좋은 예를 찾았습니다. http://docs.python.org/2/library/email-examples.html
언급 된 사이트에서 :
# Import smtplib for the actual sending function
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(textfile, 'rb')
# Create a text/plain message
msg = MIMEText(fp.read())
fp.close()
# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you
# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP('localhost')
s.sendmail(me, [you], msg.as_string())
s.quit()
"localhost"에서 연결을 허용하려면 sendmail / mailx를 올바르게 설정해야합니다. 이것은 기본적으로 내 Mac, Ubuntu 및 Redhat 서버에서 작동하지만 문제가 발생하면 다시 확인하는 것이 좋습니다.
The easiest answer is the smtplib, you can find docs on it here.
All you need to do is configure your local sendmail to accept connection from localhost, which it probably already does by default. Sure, you're still using SMTP for the transfer, but it's the local sendmail, which is basically the same as using the commandline tool.
참고URL : https://stackoverflow.com/questions/73781/sending-mail-via-sendmail-from-python
'IT TIP' 카테고리의 다른 글
| 난수 행렬을 만드는 간단한 방법 (0) | 2020.10.31 |
|---|---|
| DbSet없는 원시 SQL 쿼리-Entity Framework Core (0) | 2020.10.31 |
| 동적 변수 개수가있는 공식 (0) | 2020.10.31 |
| Rails 3.1, RSpec : 모델 유효성 검사 테스트 (0) | 2020.10.31 |
| R 데이터에서 이전 행의 값을 사용합니다. (0) | 2020.10.31 |