用户在我的页面上提交表单后,我需要发送一封电子邮件(该表单仍在开发中,但即将投入生产)。
我已经阅读了other answer,但是在提交表单后,我没有收到任何电子邮件(我将个人电子邮件用作发送者和接收者,进行了测试)。
我需要修改什么?
加号: 如何通过电子邮件发送图像?关于此的任何教程吗?提交表单后,我需要发送专业电子邮件。
settings.py
EMAIL_HOST = 'smtp.gmail.com' # since you are using a gmail account
EMAIL_PORT = 587 # Gmail SMTP port for TLS
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'oma.oma@gmail.com' #Not my actual email
EMAIL_HOST_PASSWORD = 'MyPassword' #Not my actual password
views.py:
# here we are going to use CreateView to save the Third step ModelForm
class StepThreeView(CreateView):
form_class = StepThreeForm
template_name = 'main_app/step-three.html'
success_url = '/'
def form_valid(self, form):
form.instance.tamanios = self.request.session.get('tamanios') # get tamanios from session
form.instance.cantidades = self.request.session.get('cantidades') # get cantidades from session
del self.request.session['cantidades'] # delete cantidades value from session
del self.request.session['tamanios'] # delete tamanios value from session
self.request.session.modified = True
return super(StepThreeView, self).form_valid(form)
form.py:
from django.core.mail import send_mail
class StepThreeForm(forms.ModelForm):
instrucciones = forms.CharField(widget=forms.Textarea)
class Meta:
model = TamaniosCantidades
fields = ('imagenes', 'instrucciones')
def __init__(self, *args, **kwargs):
super(StepThreeForm, self).__init__(*args, **kwargs)
self.fields['instrucciones'].required = False
def send_email(self):
send_mail('Django Test', 'My message', 'oma.oma@gmail.com',
['oma.oma@gmail.com'], fail_silently=False)
答案 0 :(得分:2)
您可以在“ Last Form”中重写save
方法,
class StepThreeForm(forms.ModelForm):
def save(self, commit=True):
instance = super(StepThreeForm, self).save(commit=commit)
self.send_email()
return instance
def send_email(self):
image = self.cleaned_data.get('imagenes', None)
msg = EmailMessage(
'Hello',
'Body goes here',
'from@example.com',
['to1@example.com', 'to2@example.com'],
headers={'Message-ID': 'foo'},
)
msg.content_subtype = "html"
if image:
mime_image = MIMEImage(image.read())
mime_image.add_header('Content-ID', '<image>')
msg.attach(mime_image)
msg.send()
您可以选中此SO Answer,以获取有关如何从Django发送图像的更多详细信息