Django邮件未以正确格式发送电子邮件吗?

时间:2019-04-03 05:32:43

标签: python django

我想将Django框架中的电子邮件发送给用户。

我设计以下脚本。当我在python ide的本地系统上运行此脚本时,它会将邮件发送给具有SUBJECT和消息正文的用户。

但是相同的代码在django框架中不起作用。它不发送主题,而消息正文仅发送消息的最后一行。

import sys
import calendar
import smtplib 
import shutil
import os
import re
from datetime import datetime, timedelta
import mysql.connector
from string import Template

import smtplib

sender = 'mywebsite@organization.com'
receivers = ['employeemail@organization.com']

message = """From: From Person <from@fromdomain.com>
            To: To Person <myemail@organization.com>
            Subject: Virus arm attack on SMTP e-mail test
This is a test e-mail message.
"""

try:
    smtpObj = smtplib.SMTP('email.organization.com')
    smtpObj.sendmail(sender, receivers, message)         
    print("Successfully sent email")
except SMTPException:
    print("Error: unable to send email")

期望的结果,这是从本地系统发送电子邮件时得到的。

主题显示为: SMTP电子邮件测试
按摩正文显示为:这是一封测试电子邮件。
谢谢

从Django框架发送邮件时的实际结果
*主题丢失,仅邮件正文打印谢谢

按摩身体显示为:

谢谢

1 个答案:

答案 0 :(得分:0)

为什么不使用Django的mailing system。它使用smtplib,但可以省去处理细节的麻烦。 只需在settings.py

中添加基本设置
# SMTP Host settings
EMAIL_HOST = ''
EMAIL_PORT = ''

# if your SMTP host needs authentication
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''

# Mail is sent using the SMTP host and port specified in the EMAIL_HOST and
# EMAIL_PORT settings. The EMAIL_HOST_USER and EMAIL_HOST_PASSWORD settings, if
# set, are used to authenticate to the SMTP server, and the EMAIL_USE_TLS and
# EMAIL_USE_SSL settings control whether a secure connection is used.

你很好。

from django.core.mail import send_mail

send_mail(
    'Subject here',
    'Here is the message.',
    'from@example.com',
    ['to@example.com'],
)
相关问题