문제

나는 Python이 새로워졌습니다 .. 실제로, 나는 Python : HTML Body, Text Alternation Body 및 Attachment와 함께 주요 이메일을 보내려고합니다.

그래서 나는 이것을 발견했다 지도 시간 Gmail 인증과 함께 적응했습니다 (자습서 발견 여기)

내가 ATM을 가진 코드는 다음과 같습니다.

def createhtmlmail (html, text, subject):
"""Create a mime-message that will render HTML in popular
  MUAs, text in better ones"""
import MimeWriter
import mimetools
import cStringIO
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import os

out = cStringIO.StringIO() # output buffer for our message 
htmlin = cStringIO.StringIO(html)
txtin = cStringIO.StringIO(text)

writer = MimeWriter.MimeWriter(out)
#
# set up some basic headers... we put subject here
# because smtplib.sendmail expects it to be in the
# message body
#
writer.addheader("Subject", subject)
writer.addheader("MIME-Version", "1.0")
#
# start the multipart section of the message
# multipart/alternative seems to work better
# on some MUAs than multipart/mixed
#
writer.startmultipartbody("alternative")
writer.flushheaders()
#
# the plain text section
#
subpart = writer.nextpart()
subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
pout = subpart.startbody("text/plain", [("charset", 'us-ascii')])
mimetools.encode(txtin, pout, 'quoted-printable')
txtin.close()
#
# start the html subpart of the message
#
subpart = writer.nextpart()
subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
#
# returns us a file-ish object we can write to
#
pout = subpart.startbody("text/html", [("charset", 'us-ascii')])
mimetools.encode(htmlin, pout, 'quoted-printable')
htmlin.close()


#
# Now that we're done, close our writer and
# return the message body
#
writer.lastpart()
msg = out.getvalue()
out.close()
return msg

import smtplib
f = open("/path/to/html/version.html", 'r')
html = f.read()
f.close()
f = open("/path/to/txt/version.txt", 'r')
text = f.read()
subject = "Prova email html da python, con allegato!"
message = createhtmlmail(html, text, subject)
gmail_user = "thegmailaccount@gmail.com"
gmail_pwd = "thegmailpassword"
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(gmail_user, gmail_pwd)
server.sendmail(gmail_user, "example@example.com", message)
server.close()

그리고 그것은 작동합니다 .. 이제 첨부 파일 만 놓치고 있습니다 .. 그리고 나는 첨부 파일을 추가 할 수 없습니다 ( 이것 게시하다)

그렇다면 PHPMailer와 같은 Python 클래스가없는 이유는 무엇입니까? 중간 정도의 Python 프로그래머가 첨부 파일과 alt 텍스트 본문이있는 HTML 이메일을 보내는 경우 클래스가 필요하지 않기 때문에 수업이 필요하지 않기 때문입니까? 아니면 방금 찾지 못했기 때문에?

내가 그런 수업을 쓸 수 있다면, Python에 충분히 좋을 때 누군가에게 유용할까요?

도움이 되었습니까?

해결책

뻔뻔스런 자기 홍보를 할 수 있다면 나는 메일러 모듈 이로 인해 Python과 함께 이메일을 보내는 것이 상당히 간단합니다. Python Smtplib 및 이메일 라이브러리 외에는 의존성이 없습니다.

다음은 첨부 파일이있는 이메일을 보내는 간단한 예입니다.

from mailer import Mailer
from mailer import Message

message = Message(From="me@example.com",
                  To=["you@example.com", "him@example.com"])
message.Subject = "Kitty with dynamite"
message.Body = """Kitty go boom!"""
message.attach("kitty.jpg")

sender = Mailer('smtp.example.com')
sender.login("username", "password")
sender.send(message)

편집하다: 다음은 대체 텍스트와 함께 HTML 이메일을 보내는 예입니다. :)

from mailer import Mailer
from mailer import Message

message = Message(From="me@example.com",
                  To="you@example.com",
                  charset="utf-8")
message.Subject = "An HTML Email"
message.Html = """This email uses <strong>HTML</strong>!"""
message.Body = """This is alternate text."""

sender = Mailer('smtp.example.com')
sender.send(message)

편집 2: 댓글 중 하나 덕분에 Mailer 클래스의 포트를 지정할 수있는 새 버전의 Mailer를 PYPI에 추가했습니다.

다른 팁

Django에는 Core에 필요한 수업이 포함되어 있으며 여기 문서

from django.core.mail import EmailMultiAlternatives

subject, from_email, to = 'hello', 'from@example.com', 'to@example.com'
text_content = 'This is an important message.'
html_content = '<p>This is an <strong>important</strong> message.</p>'
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.attach_file('/path/to/file.jpg')
msg.send()

내 설정에서 나는 다음과 같습니다.

#GMAIL STUFF
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'name@gmail.com'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PORT = 587

그냥 가리키고 싶어요 램슨 프로젝트 내가이 스레드를 찾았을 때 내가 찾고 있던 것이 었습니다. 나는 좀 더 검색을하고 그것을 발견했다. 그것의:

Lamson의 목표는 "이메일 응용 프로그램 개발"인 지옥을 끝내는 것입니다. Lamson은 1970 년대에 갇히지 않고 현대 웹 애플리케이션 프레임 워크 설계를 채택하고 입증 된 스크립팅 언어 (Python)를 사용합니다.

Django와 잘 통합됩니다. 그러나 이메일 기반 응용 프로그램을 위해 더 많이 만들어졌습니다. 그래도 순수한 사랑처럼 보입니다.

어쩌면 당신은 함께 시도 할 수 있습니다 터보 메일 python-turbomail.org

더 쉽고 유용합니다 :)

import turbomail

# ...

message = turbomail.Message("from@example.com", "to@example.com", subject)
message.plain = "Hello world!"

turbomail.enqueue(message)

나는 그것을 읽는 것이 좋습니다 SMTP RFC. Google 검색에 따르면 가져오고 있지만 사용하지 않는 Mimemultipart 클래스를 사용하여 쉽게 수행 할 수 있습니다. 여기에 있습니다 몇 가지 예 Python의 문서 사이트에서.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top