Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python을 사용하여 이메일로 첨부 파일 보내기

<시간/>

혼합 콘텐츠가 포함된 이메일을 보내려면 콘텐츠 유형을 설정해야 합니다. multipart/mixed 헤더 . 그런 다음 경계 내에서 텍스트 및 첨부 파일 섹션을 지정할 수 있습니다. .

경계는 두 개의 하이픈으로 시작하고 그 뒤에 고유 번호가 옵니다. 이 번호는 전자 메일의 메시지 부분에 나타날 수 없습니다. 이메일의 마지막 섹션을 나타내는 마지막 경계도 두 개의 하이픈으로 끝나야 합니다.

첨부 파일은 pack("m")으로 인코딩해야 합니다. 전송하기 전에 base64로 인코딩하는 기능입니다.

예시

다음은 /tmp/test.txt 파일을 보내는 예입니다. 첨부 파일로. 한 번 시도해 보세요 -

#!/usr/bin/python
import smtplib
import base64
filename = "/tmp/test.txt"
# Read a file and encode it into base64 format
fo = open(filename, "rb")
filecontent = fo.read()
encodedcontent = base64.b64encode(filecontent) # base64
sender = 'webmaster@tutorialpoint.com'
reciever = 'amrood.admin@gmail.com'
marker = "AUNIQUEMARKER"
body ="""
This is a test email to send an attachement.
"""
# Define the main headers.
part1 = """From: From Person <me@fromdomain.net>
To: To Person <amrood.admin@gmail.com>
Subject: Sending Attachement
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)
# Define the message action
part2 = """Content-Type: text/plain
Content-Transfer-Encoding:8bit
%s
--%s
""" % (body,marker)
# Define the attachment section
part3 = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename=%s
%s
--%s--
""" %(filename, filename, encodedcontent, marker)
message = part1 + part2 + part3
try:
   smtpObj = smtplib.SMTP('localhost')
   smtpObj.sendmail(sender, reciever, message)
   print "Successfully sent email"
except Exception:
   print "Error: unable to send email"