Я пытался отправить электронную почту через smtp и email.mime с Django. Я решил не использовать электронную почту django, потому что я хочу автоматизировать отправку электронных писем на несколько других электронных писем от любого пользователя, поэтому пользователь должен будет ввести свой адрес электронной почты и пароль в свой адрес электронной почты, чтобы smtp мог отправлять электронные письма, используя свою учетную запись. на другие электронные письма
Internal Server Error: /api/email/1/send/
Traceback (most recent call last):
File "/home/taycode/Desktop/emailsenderapi/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/taycode/Desktop/emailsenderapi/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/taycode/Desktop/emailsenderapi/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/taycode/Desktop/emailsenderapi/env/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/taycode/Desktop/emailsenderapi/env/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "/home/taycode/Desktop/emailsenderapi/env/lib/python3.6/site-packages/rest_framework/views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "/home/taycode/Desktop/emailsenderapi/env/lib/python3.6/site-packages/rest_framework/views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/taycode/Desktop/emailsenderapi/env/lib/python3.6/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
raise exc
File "/home/taycode/Desktop/emailsenderapi/env/lib/python3.6/site-packages/rest_framework/views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "/home/taycode/Desktop/emailsenderapi/api/views.py", line 71, in post
serializer.send(email_object_id=pk, validated_data=serializer.validated_data)
File "/home/taycode/Desktop/emailsenderapi/api/serializers.py", line 61, in send
sender.send()
File "/home/taycode/Desktop/emailsenderapi/api/utils.py", line 44, in send
self.s.send_message(msg=self.msg)
File "/usr/lib/python3.6/smtplib.py", line 936, in send_message
from_addr = email.utils.getaddresses([from_addr])[0][1]
File "/usr/lib/python3.6/email/utils.py", line 112, in getaddresses
all = COMMASPACE.join(fieldvalues)
TypeError: sequence item 0: expected str instance, NoneType found
Это мой класс отправителя, который я создал
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
from os.path import basename
class Sender:
def __init__(self, email, password):
host = "smtp.gmail.com"
port = 587
self.email = email
self.s = smtplib.SMTP(host=host, port=port)
self.s.starttls()
self.s.login(email, password)
self.msg = MIMEMultipart()
def add_attachments(self, path):
with open(path, "rb") as fil:
part = MIMEApplication(
fil.read(),
Name=basename(path)
)
# After the file is closed
part['Content-Disposition'] = 'attachment; filename="%s"' % basename(path)
self.msg.attach(part)
def add_body(self, body):
self.msg.attach(MIMEText(body, "plain"))
return self.msg
def add_recipient(self, email):
self.msg['To'] = email
return self.msg
def add_subject(self, subject):
self.msg['subject'] = subject
return self.msg
def send(self):
print(dict(self.msg))
print(self.s)
self.s.send_message(msg=self.msg)
del self.msg
self.s.quit()
Это мой serializer.py
from sender.models import EmailObject
from .utils import Sender
class SendEmailSerializer(Serializer):
email = serializers.EmailField()
password = serializers.CharField()
@staticmethod
def send(validated_data, **kwargs):
email_object = EmailObject.objects.get(pk=kwargs['email_object_id'])
for recipient in email_object.recipient.all():
sender = Sender(validated_data['email'], validated_data['password'])
sender.add_recipient(str(recipient.email))
sender.add_body(email_object.body)
sender.add_subject(email_object.subject)
for attachment in email_object.attachments.all():
print(attachment.file.path)
sender.add_attachments(attachment.file.path)
sender.send()
Это мои views.py
class SendEmail(APIView):
serializer_class = SendEmailSerializer
@staticmethod
def post(request, pk):
serializer = SendEmailSerializer(data=request.data)
if serializer.is_valid():
print(serializer.validated_data)
serializer.send(email_object_id=pk, validated_data=serializer.validated_data)
data = {'status': 'success'}
return Response(data, status=status.HTTP_200_OK)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Он возвращает ошибку каждый раз, когда я вызываю представление SendEmail в views.py. как я могу это исправить ??