Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Django send_mail newlines?

I'm using django send_mail like this:

from django.core.mail import send_mail

send_mail('Test', 'asdfasdfasdf\nasdfasfasdfasdf\nasdfasdfasdf', '[email protected]', ['[email protected]'], fail_silently=False)

Gmail recieves this.

Content-type: multipart/alternative; boundary="----------=_1382512224-21042-56"
------------=_1382512224-21042-56
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit

asdfasdfasdf
asdfasfasdfasdf
asdfasdfasdf

------------=_1382512224-21042-56
Content-Type: text/html; charset="utf-8"
Content-Disposition: inline
Content-Transfer-Encoding: 7bit

<html><body>
<p>asdfasdfasdf asdfasfasdfasdf asdfasdfasdf</p>
</body></html>

And shows my newlines as one whole paragraph. Why? I would like three lines of text, not one.

like image 278
heffaklump Avatar asked Oct 23 '13 07:10

heffaklump


2 Answers

Try sending your email as HTML instead of plain text. Use EmailMessage().

from django.core.mail import EmailMessage

msg = EmailMessage(
    'Test',
    'asdfasdfasdf<br>asdfasfasdfasdf<br>asdfasdfasdf',
    '[email protected]',
    ['[email protected]', ]
)
msg.content_subtype = "html"
msg.send()
like image 193
arulmr Avatar answered Oct 15 '22 04:10

arulmr


If you want control over the different components of the mutlipart e-mail, you can create a EmailMultiAlternatives and then .send() the email message you created.

Django's exmample from the documentation.

from django.core.mail import EmailMultiAlternatives

subject, from_email, to = 'hello', '[email protected]', '[email protected]'
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.send()
like image 38
Tim Edgar Avatar answered Oct 15 '22 02:10

Tim Edgar