Python3 SMTP 发送邮件时如何解决编码问题?
最近在跟着学习廖雪峰的 Python 教程,到发送邮件这一章出现了编码问题,搜索一直得不到解决,特来求助广大 V 友。
以下是代码部分:
from email.mime.text import MIMEText
msg = MIMEText(‘hello, send by Python…’, ‘plain’, ‘utf-8’)
输入 Email 地址和口令:
from_addr = input('From: ')
password = input('Password: ')
输入收件人地址:
to_addr = input('To: ')
输入 SMTP 服务器地址:
smtp_server = input('SMTP server: ')
import smtplib
server = smtplib.SMTP(smtp_server, 25)
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()
报错:
SMTP server: smtp.qq.com
send: 'ehlo Sakuoz 丶.lan\r\n'
Traceback (most recent call last):
File "F:\github\pythonTest\pytest.py", line 16, in <module>
server.login(from_addr, password)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\smtplib.py", line 693, in login
self.ehlo_or_helo_if_needed()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\smtplib.py", line 599, in ehlo_or_helo_if_needed
if not (200 <= self.ehlo()[0] <= 299):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\smtplib.py", line 439, in ehlo
self.putcmd(self.ehlo_msg, name or self.local_hostname)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\smtplib.py", line 366, in putcmd
self.send(str)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\smtplib.py", line 351, in send
s = s.encode(self.command_encoding)
UnicodeEncodeError: 'ascii' codec can't encode character '\u4e36' in position 11: ordinal not in range(128)
\u4e36 经过 unicode 转换为中文丶,我发送的邮件( QQ to 163 )昵称中也有个丶,所以怀疑可能与昵称有关,但是经过测试删掉昵称中的丶还是报同样的错误,萌新的我一直不知道错在什么地方。。。请问问题出在哪里,该怎么解决,谢谢大家!
开发环境:
- windows 10 64bit
- python 3.5.2
- atom
Python3 SMTP 发送邮件时如何解决编码问题?
self.putcmd(self.ehlo_msg, name or self.local_hostname)
你的主机名有中文吧。
核心问题: 邮件主题和正文的编码设置不正确,导致接收方显示乱码。
解决方案: 使用 email 库的 MIMEText 或 MIMEMultipart 正确设置字符编码,特别是对中文等非ASCII字符。
关键代码示例:
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 邮件配置
smtp_server = "smtp.example.com"
smtp_port = 587
sender = "your_email@example.com"
password = "your_password"
receiver = "recipient@example.com"
# 创建邮件内容(包含中文)
subject = "测试邮件主题"
body = "这是一封测试邮件,包含中文内容。"
# 正确设置编码:关键步骤!
msg = MIMEText(body, 'plain', 'utf-8')
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] = sender
msg['To'] = receiver
# 发送邮件
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(sender, password)
server.send_message(msg)
print("邮件发送成功")
except Exception as e:
print(f"发送失败: {e}")
finally:
server.quit()
重点说明:
MIMEText(body, 'plain', 'utf-8'):第三个参数指定邮件正文的编码为UTF-8。Header(subject, 'utf-8'):使用Header对象包装主题,并指定UTF-8编码。- 确保你的SMTP服务器支持TLS(如使用Gmail、QQ等)。
一句话总结: 用MIMEText和Header显式指定UTF-8编码。
你输入的昵称出现在哪里? from_addr to_addr 都不允许直接传昵称
好像是,我最近无聊改过一次,我去试试
没有传,以上就是全部代码,没一句中文-_-||
好吧……那有可能是主机名问题
谢谢楼上二位,已解决,真的是主机名问题,一直都没往这个方向想,学习了,自己没事瞎改啥主机名(捂脸)
结贴

