문제

내 웹 애플리케이션에서는 다음과 같이 재사용 가능한 메일러 애플리케이션을 사용하여 가끔 이메일을 보냅니다.

user - self.user
subject = ("My subject")
from = "me@mydomain.com"
message = render_to_string("welcomeEmail/welcome.eml", { 
                "user" : user,
                })
send_mail(subject, message, from, [email], priority="high" )

이미지가 포함된 이메일을 보내고 싶어서 메일 클라이언트에서 메일을 작성하고 소스를 확인한 후 템플릿(welcome.eml)에 넣어 보았지만 렌더링할 수 없었습니다. 전송 시 메일 클라이언트에서 올바르게 표시됩니다.

보낼 때 올바르게 렌더링되는 인라인 이미지가 포함된 MIME 인코딩 메일 템플릿을 만드는 쉬운 방법을 아는 사람이 있습니까?

도움이 되었습니까?

해결책

업데이트

많은 감사 사킵 알리 내 답변이 있은 지 거의 5년이 지나서 이 오래된 질문을 부활시켜 주셔서 감사합니다.

당시 내가 준 지시는 더 이상 작동하지 않습니다.나는 그 사이에 Django에 약간의 개선이 있었다고 생각합니다. send_mail() 일반 텍스트를 적용합니다.내용에 무엇을 넣든 항상 일반 텍스트로 전달됩니다.

가장 최근에 장고 문서 그것을 설명한다 send_mail() 실제로는 인스턴스를 생성하기 위한 편의일 뿐입니다. django.core.mail.EmailMessage 수업을 마치고 전화를 걸어 send() 그 경우에는. EmailMessage 2014년 현재 보고 있는 결과를 설명하는 body 매개변수에 대한 다음 메모가 있습니다.

몸:본문 텍스트입니다.일반 텍스트 메시지여야 합니다.

...다소 나중에 문서에서 ...

기본적으로 EmailMessage의 본문 매개변수의 MIME 유형은 "text/plain"입니다.이것을 그대로 두는 것이 좋습니다.

충분히 그렇습니다(2009년 지침이 왜 작동했는지 조사할 시간을 갖지 않았다는 것을 고백합니다. 2009년에 다시 테스트했거나 변경되었을 때).Django는 제공하며, 문서, ㅏ django.core.mail.EmailMultiAlternatives 동일한 메시지의 일반 텍스트와 HTML 표현을 더 쉽게 보낼 수 있도록 하는 클래스입니다.

이 질문의 경우는 약간 다릅니다.우리는 대안 자체를 추가하려는 것이 아니라 추가하려고 합니다. 관련된 대안 중 하나에 대한 부분입니다.HTML 버전 내에서(일반 텍스트 버전이 있는지 여부는 중요하지 않음) 이미지 데이터 부분을 삽입하려고 합니다.내용에 대한 대안적인 견해는 아니지만, 관련된 HTML 본문에서 참조되는 콘텐츠입니다.

포함된 이미지를 보내는 것은 여전히 ​​가능하지만 다음을 사용하여 이를 수행하는 간단한 방법은 없습니다. send_mail.이제 편의 기능을 생략하고 인스턴스화할 시간입니다. EmailMessage 곧장.

이전 예에 대한 업데이트는 다음과 같습니다.

from django.core.mail import EmailMessage
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# Load the image you want to send as bytes
img_data = open('logo.jpg', 'rb').read()

# Create a "related" message container that will hold the HTML 
# message and the image. These are "related" (not "alternative")
# because they are different, unique parts of the HTML message,
# not alternative (html vs. plain text) views of the same content.
html_part = MIMEMultipart(_subtype='related')

# Create the body with HTML. Note that the image, since it is inline, is 
# referenced with the URL cid:myimage... you should take care to make
# "myimage" unique
body = MIMEText('<p>Hello <img src="cid:myimage" /></p>', _subtype='html')
html_part.attach(body)

# Now create the MIME container for the image
img = MIMEImage(img_data, 'jpeg')
img.add_header('Content-Id', '<myimage>')  # angle brackets are important
img.add_header("Content-Disposition", "inline", filename="myimage") # David Hess recommended this edit
html_part.attach(img)

# Configure and send an EmailMessage
# Note we are passing None for the body (the 2nd parameter). You could pass plain text
# to create an alternative part for this message
msg = EmailMessage('Subject Line', None, 'foo@bar.com', ['bar@foo.com'])
msg.attach(html_part) # Attach the raw MIMEBase descendant. This is a public method on EmailMessage
msg.send()

2009년의 원래 답변:

이미지가 포함된 이메일을 보내려면 Python에 내장된 이메일 모듈을 사용하여 MIME 부분을 구축하세요.

다음을 수행해야 합니다.

from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# Load the image you want to send at bytes
img_data = open('logo.jpg', 'rb').read()

# Create a "related" message container that will hold the HTML 
# message and the image
msg = MIMEMultipart(_subtype='related')

# Create the body with HTML. Note that the image, since it is inline, is 
# referenced with the URL cid:myimage... you should take care to make
# "myimage" unique
body = MIMEText('<p>Hello <img src="cid:myimage" /></p>', _subtype='html')
msg.attach(body)

# Now create the MIME container for the image
img = MIMEImage(img_data, 'jpeg')
img.add_header('Content-Id', '<myimage>')  # angle brackets are important
msg.attach(img)

send_mail(subject, msg.as_string(), from, [to], priority="high")

실제로는 일반 텍스트 대안과 함께 HTML을 보내고 싶을 수도 있습니다.이 경우 MIMEMultipart를 사용하여 "관련" MIME 유형 컨테이너를 루트로 만듭니다.그런 다음 "대체" 하위 유형으로 다른 MIMEMultipart를 만들고 MIMEText(하위 유형 html)와 MIMEText(일반 하위 유형)를 모두 대체 부분에 첨부합니다.그런 다음 관련 루트에 이미지를 첨부합니다.

다른 팁

Django 1.10에서 Jarret의 레시피에 어려움을 겪고있었습니다. MIME 데이터를 첨부 할 수있는 다양한 방법에 대한 MIME를 얻고 오류를 인코딩했습니다.

다음은 임베디드가있는 이메일을위한 간단한 멀티 파트 트랜잭션 템플릿입니다. coupon_image django 1.10에서 작동하는 파일 객체 :

from django.core.mail import EmailMultiAlternatives
from email.mime.image import MIMEImage

def send_mail(coupon_image):
    params = {'foo':'bar'} # create a template context
    text_body = render_to_string('coupon_email.txt', params)
    html_body = render_to_string('coupon_email.html', params)
    img_data = coupon_image.read() #should be a file object, or ImageField
    img = MIMEImage(img_data)
    img.add_header('Content-ID', '<coupon_image>')
    img.add_header('Content-Disposition', 'inline', filename="coupon_image")

    email = EmailMultiAlternatives(
        subject="Here's your coupon!",
        body=text_body,
        from_email='noreply@example.com',
        to=['someone@example.com',]
    )

    email.attach_alternative(html_body, "text/html")
    email.mixed_subtype = 'related'
    email.attach(img)

    email.send(fail_silently=False)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top