Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

เข้ารหัสและถอดรหัสข้อมูล MIME quoted-printable ด้วย Python

เมื่อต้องจัดการข้อมูลที่มีอักขระนอกเหนือจาก ASCII มาตรฐาน เช่น อีเมลในภาษาต่างประเทศ Python มีโมดูลที่รองรับ MIME (Multipurpose Internet Mail Extensions) เพื่อจัดการการเข้ารหัสและถอดรหัส quoted-printable

การใช้งานแพ็กเกจ email

แพ็กเกจ email มีโมดูล mime และ charset ที่ช่วยเข้ารหัส/ถอดรหัสได้ ตัวอย่างด้านล่างสร้างข้อความอีเมลที่มีอักขระ Unicode และเข้ารหัสเป็น UTF-8

import email.mime, email.mime.nonmultipart, email.charset

msg = email.mime.nonmultipart.MIMENonMultipart('text', 'plain', charset='utf-8')
cs = email.charset.Charset('utf-8')
cs.body_encoding = email.charset.QP
msg.set_payload(u'This is the text containing \u00fcnic\u00f6de', charset=cs)
print(msg)

ผลลัพธ์

Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: quoted-printable
This is the text containing =C3=BCnic=C3=B6de

การใช้งานโมดูล quopri

โมดูล quopri ทำ quoted-printable transport encoding/decoding เหมาะสำหรับข้อมูลที่มีอักขระ non-printable น้อย

import quopri

str1 = '\u00e4\u00e9'
encoded = quopri.encodestring(str1.encode('utf-8'))
print(encoded)

str2 = '=C3=A4=C3=A9'
decoded_string = quopri.decodestring(str2)
print(decoded_string.decode('utf-8'))

ผลลัพธ์

b'=C3=A4=C3=A9'
äé