[英]Sending Email attachment using django :
i am trying to attach file and send it to email . 我正在尝试附加文件并将其发送到电子邮件。 but it is redirecting me to an error page ie error.html.
但是它将我重定向到错误页面,即error.html。 File is not getting send to email.
文件没有发送到电子邮件。 Can u plz help me with this error .
你能帮我解决这个错误吗? I am a newbie in django, your help be appreciated.
我是django的新手,感谢您的帮助。 ThankYou
谢谢
class Email(models.Model):
email = models.EmailField()
subject = models.CharField(max_length=100)
attach = models.FileField()
message = models.CharField(max_length=250)
from django import forms
from .models import Email
from django.core.mail import EmailMessage
class EmailForm(forms.ModelForm):
class Meta:
model = Email
fields = ['email', 'attach','subject' ,'message']
def _clean_email(self):
email = self.cleaned_data.get('email')
return email
def _clean_subject(self):
subject = self.cleaned_data.get('subject')
return subject
def _clean_message(self):
message = self.cleaned_data.get('message')
return message
def _clean_attach(self):
attach = self.cleaned_data.get('attach')
return attach
def send_email(request):
if request.method != 'POST':
form = EmailForm()
context = {
"form": form
}
return render(request,'email.html', context)
form = EmailForm(request.POST, request.FILES)
if form.is_valid():
subject = form.cleaned_data.get("subject")
message = form.cleaned_data.get("message")
email = form.cleaned_data.get("email")
a = request.FILES['attach']
try:
mail = EmailMessage(subject, message, settings.EMAIL_HOST_USER, 'vamagithub@gmail.com')
mail.attach_file(a.name, a.read(), a.content_type)
mail.send()
context ={
"message": 'Sent email to %s' % email
}
return render(request,'email.html',context)
except:
context = {
"message": 'Either the attachment is too big or corrupt'
}
return render(request,'error.html',context)
return render(request,'email.html', {'message': 'Unable to send email. Please try again later'})
You have used attach_file. 您已使用attach_file。 In that you have to provide path of the file for passing these parameters a.name, a.read(), a.content_type.
为此,您必须提供用于传递这些参数a.name,a.read(),a.content_type的文件路径。 You use only attach(a.name, a.read(), a.content_type).
您仅使用attach(a.name,a.read(),a.content_type)。 For more information, read this
有关更多信息,请阅读此
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.