我是初学者,使用了从https://docs.djangoproject.com/en/2.0/topics/email/发送电子邮件的步骤 但是我没有完成发送电子邮件的任务。
我想在用户提交表单后使用django电子邮件自动发送电子邮件。我有一个预订表格,并且在用户发布表格后在其中有一个电子邮件字段,我想发送一封电子邮件“谢谢您的预订/您的预订已放置”。
例如
我要使用any@gmail.com并向其发送电子邮件。用户发布表单后。
settings.py
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'my@gmail.com'
EMAIL_HOST_PASSWORD = 'mypassword'
EMAIL_USE_TLS = True
View.py
class BookingView(FormView):
template_name = 'buggy_app/booking.html'
form_class = BookingForm
models = Booking
def form_valid(self, form):
car_id = self.request.GET.get('car', '')
car = Car.objects.get(id=car_id)
car.is_available_car = False
car.save()
form.save()
return super(BookingView, self).form_valid(form)
success_url = reverse_lazy('index')
Forms.py
class BookingForm(ModelForm):
class Meta:
model = Booking
widgets = {
times_pick': TimePickerInput(), }
fields = ('first_name','last_name','email','book_car','contact_number','times_pick',)
答案 0 :(得分:0)
您可以定义一个名为send_emails(或任何名称)的函数。并从form_valid方法中调用taht函数。看起来像这样
def form_valid(self, form):
car_id = self.request.GET.get('car', '')
car = Car.objects.get(id=car_id)
car.is_available_car = False
car.save()
form.save()
form.cleaned_data.get('username')
first_name = form.cleaned_data.get('first_name')
last_name = form.cleaned_data.get('last_name')
to_email = form.cleaned_data.get('email')
#your function here
send_emails(first_name, last_name, to_email)
然后定义类似这样的功能。
def send_emails(first_name, last_name, to_email):
#get template
htmly = get_template('email_templates/welcome.html')
#create a context
d = {'first_name':first_name, 'last_name':last_name}
subject, from_email, to = 'Subject line', settings.EMAIL_HOST_USER, to_email
#pass the context to html template
html_content = htmly.render(d)
msg = EmailMultiAlternatives(subject, html_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()