python - Django rest 框架:sendgrid email with attachment without model only filefield to open file and send button to send email
问题描述
我是 Django Rest 框架的新手。
我正在尝试发送带有附件的电子邮件。
这是我的代码。
模型.py
class EmailModel(models.Model):
upload_file = models.FileField(upload_to='location/location/files', blank=False)
class Meta:
verbose_name = 'Applicant CSV Upload'
verbose_name_plural = 'Applicant CSV Upload'
管理员.py
@admin.register(EmailModel)
class EmailAdmin(admin.ModelAdmin):
class Meta:
model = EmailModel
视图.py
def send_email():
email = EmailMessage(
'Title',
('abc', 'abc@gmail.com', '123123123'),
'abc@gmail.com',
['abc@gmail.com']
)
email.attach_file(EmailViewSet.upload_file)
email.send()
class EmailViewSet(viewsets.ModelViewSet):
queryset = EmailModel.objects.all()
serializer_class = EmailSerializer
def create(self, request, *args, **kwargs):
send_mail(' Test Subject here', 'Test here is the message.', 'abc@gmail.com', ['abc@gmail.com'], fail_silently=False)
response = super(EmailViewSet, self).create(request, *args, **kwargs)
send_email() # sending mail
data = [{'location': request.data.get('location'), 'image': file} for file in request.FILES.getlist('image')]
serializer = self.get_serializer(data=data, many=True)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
message = EmailMessage(subject='Applicant data', body='PFA', from_email='abc@gmail.com',
to='abc@gmail.com', bcc='abc@gmail.com', connection=None,
attachments=data, headers=self.data, cc='abc@gmail.com', reply_to=None)
# Attach file
# with open(attachment, 'rb') as file:
# message.attachments = [
# (attachment, file.read(), 'application/pdf')
# ]
return response, message.send(), Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
序列化程序.py
class EmailSerializer(serializers.ModelSerializer):
class Meta:
model = EmailModel
fields = ('upload_file',)
设置.py
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey' # this is exactly the value 'apikey'
EMAIL_HOST_PASSWORD = 'here i am using my sendgrid api key directy' # this is your API key
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
DEFAULT_FROM_EMAIL = 'here i am using same gmail id on which i have created my send grid account'
在 view.py 和 serializer.py 中,我提到了我尝试发送电子邮件的每一种方法,这就是为什么它如此混乱。任何方法都不起作用。甚至create
方法根本不调用。
这显示在我的 api 管理员上,我想更改要发送的保存按钮文本。
- 我不想创建模型。它是为在管理员上显示此文件而创建的,我需要模型。
- 也不想将文件保存在文件夹中。这是节省。
- filefiled 只需打开文件并在我的硬编码电子邮件地址上按保存/发送按钮时通过电子邮件发送该文件。
解决方案
推荐阅读
- ios - UITextFields 不显示,也不显示 TableView
- reactjs - 带有 Reactjs 的 MediaElement.js
- reactjs - 使用参数反应重定向
- macos - 在任意二进制文件的 MacOS 上更改进程名称
- awk - 使用 awk sub 以数字方式为字符串添加前缀而不更改计数状态最多 5 个匹配“在每行具有多个匹配项的文本文件中”
- node.js - Express 会话在 localhost 上工作,但在托管后不工作
- javascript - 在javascript中的父类中导入子类
- python-3.x - 使用 PyPi 的 Covid 包,我得到“对象没有此属性”,但文档另有说明
- swift - 使用 TextField 在 VStack 中隐藏它下面的 ScrollView
- reactjs - 将数组的 usestate 挂钩设置为 [](空数组)不起作用