Exception Type: UnicodeEncodeError

CentOS Stream 9
Python 3.9.12

メールを送信するAPIをテストで作成しています。
英文のメールは送信できるのですが、日本語だと以下のエラーが出力されます。

Exception Type: UnicodeEncodeError
Exception Value:
'ascii' codec can't encode character '\u3042' in position 32: ordinal not in range(128)

コードは以下になります。

# -*- coding: utf_8 -*- from rest_framework import status from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response import subprocess class Mail(APIView): def post(self, request, *args, **kwargs): subject = 'あ' message = 'This is a test mail.' cmd = "echo -e '" + message + "' | mail -s '" + subject + "' test@test.com" subprocess.run(cmd, shell=True, encoding="utf_8", universal_newlines=True) return Response(status.HTTP_200_OK)

色々と調べたところ、subprocess.run() の引数に encoding="utf_8", universal_newlines=True をつければうまくいくと書いてありましたが、状況は変わりません。

解決方法をご存知の方がいれば教えていただきたいです。

以下のコマンドでサーバーから日本語メールを送れるので、Pythonの方の問題だと思っています。

echo -e 'This is a test mail.' | mail -s 'あ' test@test.com

コメントを投稿

0 コメント