乱码问题

import sys
import locale
sys.getdefaultencoding()  # 返回当前系统所使用的默认字符编码。例如,返回值:‘utf-8'
sys.getfilesystemencoding()  #返回用于转换Unicode文件名至系统文件名所使用的编码
locale.getdefaultlocale()  #获取默认的区域设置并返回元组(语言, 编码)。例如,返回值:(’zh_CN','cp936')
locale.getpreferredencoding()  #返回用户设定的文本数据编码,文档提到this function only returns a guess

sys.setdefaultencoding('utf8')  #设置系统默认编码

cp936就是指系统里第936号编码格式,也就是GB2312,如excel中倒入CSV数据。 微软的CP936通常被视为等同GBK,连 IANA 也以“CP936”为“GBK”之别名[1]。事实上比较起来, GBK 定义之字符较 CP936 多出95字(15个非汉字及80个汉字)。


CP936和UTF-8本身和Python是毫无关联的。
CP936其实就是GBK,IBM在发明Code Page的时候将GBK放在第936页,所以叫CP936。
至于GBK,百度百科就说的很清楚了:

GBK全称《汉字内码扩展规范》(GBK即“国标”、“扩展”汉语拼音的第一个字母,英文名称:Chinese Internal Code Specification) ,中华人民共和国全国信息技术标准化技术委员会1995年12月1日制订,国家技术监督局标准化司、电子工业部科技与质量监督司1995年12月15日联合以技监标函1995 229号文件的形式,将它确定为技术规范指导性文件。这一版的GBK规范为1.0版。

UTF-8: UTF-8(8-bit Unicode Transformation Format)是一种针对Unicode的可变长度字符编码,又称万国码。由Ken Thompson于1992年创建。现在已经标准化为RFC 3629。UTF-8用1到6个字节编码UNICODE字符。用在网页上可以同一页面显示中文简体繁体及其它语言(如英文,日文,韩文)。

所以GBK和UTF-8简单的来说,区别就是编码方式不同,表示的文字范围不同。(UTF-8能表示更多的语言文字,更加通用)在Python里面,你需要注意你Python本身是否声明了字符编码类型(尤其是Py 2x),例如:#-*- coding: UTF-8 -*-
以及,你是如何从外部文件或者网页读入字符的,他们的源编码类型是什么。必要的时候,使用decode和encode。

 

NameError: name 'unicode' is not defined

Python3中语句:isinstance(subject,unicode),提示:NameError: name 'unicode' is not defined.

Python isinstance() 函数 | 菜鸟教程  http://www.runoob.com/python/python-func-isinstance.html

There is no such name in Python 3, no. You are trying to run Python 2 code in Python 3. In Python 3, unicode has been renamed to str. Python2 的unicode 函数在 Python3 中被命名为 str。

正确语句:isinstance(subject,str)

try语句不完整引起:Syntax error “unexpected unindent”

try:语句后,不做异常处理,抛出:Syntax error “unexpected unindent”。try:须与except Exception:成对出现 。补充except Exception语句后,运行正常。

 

# -*- coding: utf-8 -*-

"""
Module implementing Dialog.
"""

from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QDialog
from PyQt5 import QtWidgets
from Ui_tr import Ui_Dialog
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.utils import parseaddr,formataddr


fromMail = 'aa@aa.com'
host='mail.aa.com'
user='aa@aa.com'
password='bb'

class Dialog(QDialog, Ui_Dialog):
    """
    Class documentation goes here.
    """

    def __init__(self, parent=None):

        super(Dialog, self).__init__(parent)
        self.setupUi(self)
    
    @pyqtSlot()
    def on_pushButton_clicked(self):
        print('ad')
        sendMail("aa@163.com", "主题", '正文',format='plain')
        sendMail("aa@qq.com", "主题", '正文',format='plain')
        





def sendMail(mailto,subject,body,format='plain'):
    if isinstance(body,str):
        body = str(body)

    _mailFrom='发送人姓名'
    me= ("%s<"+fromMail+">") % (Header(_mailFrom,'utf-8'),)
    print("me:", me)
    msg = MIMEText(body,format,'utf-8')
    if not isinstance(subject,str):
        subject = unicode(subject)
    msg['Subject'] = subject
    msg['From'] = me
    msg['To'] = mailto
    msg["Accept-Language"]="zh-CN"
    msg["Accept-Charset"]="ISO-8859-1,utf-8"
    try:
        s = smtplib.SMTP()
        s.connect(host, 25)
        print("hostst:", s.connect(host))
        s.login(user,password)
        print("ddddd", s.login(user,password))
        s.sendmail(me, mailto, msg.as_string())
        print("发件成功")
        s.close()
    except Exception:  
        print("异常")

if __name__ == "__main__":
    import sys
    app=QtWidgets.QApplication(sys.argv)
    ui=Dialog()
    ui.show()
    sys.exit(app.exec())

bytes can only contain ASCII literal characters.

UTF-8与GBK互转,为什么会乱码 - 洋成林 - 优快云博客  https://blog.youkuaiyun.com/yangfengjueqi/article/details/79486162

Python编程——总目录 - bluewater的专栏 - 优快云博客  https://blog.youkuaiyun.com/sjpljr/article/details/79194295

UTF-8/GBK编码在线转换工具  http://www.soupan.info/tool/utf-8.php

UTF-8 转换工具 - 站长工具  http://tool.chinaz.com/Tools/UTF-8.aspx

python自动发送邮件自定义邮件发件人和收件人的显示内容 - qq32712784的博客 - 优快云博客  https://blog.youkuaiyun.com/qq32712784/article/details/48582945

发件人姓名,发件人地址

详细讲解用Python发送SMTP邮件的教程_python_脚本之家  https://www.jb51.net/article/65172.htm很好

Python使用email模块对邮件进行编码和解码的实例教程_python_脚本之家  https://www.jb51.net/article/87784.htm

python发邮件:

邮件的格式:

  • 邮件主题;
  • 发件人、收件人显示友好的名字,比如Mr Green <green@example.com>,而不是green <green@example.com>
  • 明明收到了邮件,却提示不在收件人中。

SMTP是发送邮件的协议,Python内置对SMTP的支持,可以发送纯文本邮件、HTML邮件以及带附件的邮件。

Python对SMTP支持有smtplib和email两个模块,email负责构造邮件,smtplib负责发送邮件。

from email.mime.text import MIMEText
msg = MIMEText('hello, send by Python...', 'plain', 'utf-8')

注意到构造MIMEText对象时,第一个参数就是邮件正文,第二个参数是MIME的subtype,传入'plain',最终的MIME就是'text/plain',最后一定要用utf-8编码保证多语言兼容性。

然后,通过SMTP发出去:

# 输入Email地址和口令:
from_addr = input('From: ')
password = input('Password: ')
# 输入SMTP服务器地址:
smtp_server = input('SMTP server: ')
# 输入收件人地址:
to_addr = input('To: ')
 
import smtplib
server = smtplib.SMTP(smtp_server, 25) # SMTP协议默认端口是25
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()

基础邮件原理(MUA,MTA,MDA) -   https://blog.youkuaiyun.com/z59d8m6e40/article/details/72871485

我们用set_debuglevel(1)就可以打印出和SMTP服务器交互的所有信息。SMTP协议就是简单的文本命令和响应。login()方法用来登录SMTP服务器,sendmail()方法就是发邮件,由于可以一次发给多个人,所以传入一个list,邮件正文是一个str,as_string()把MIMEText对象变成str。

parseaddr示例:

>>> import email.utils
>>> email.utils.parseaddr('tim_spac@126.com')
('', 'tim_spac@126.com')
>>> email.utils.parseaddr('"Lao Wang" <tim_spac@126.com>')
('Lao Wang', 'tim_spac@126.com')

 

'bytes' object has no attribute 'encode'

python3中,编码的时候区分了字符串和二进制,encode 改为 decode ,但改完就提示如下:

'str' object has no attribute 'decode'

python 3中只有unicode str,decode方法去掉了。

如果我们查看Email的原始内容,可以看到如下经过编码的邮件头:

From: =?utf-8?b?UHl0aG9u54ix5aW96ICF?= <xxxxxx@163.com>
To: =?utf-8?b?566h55CG5ZGY?= <xxxxxx@qq.com>
Subject: =?utf-8?b?5p2l6IeqU01UUOeahOmXruWAmeKApuKApg==?=

 

UTF-8和GBK等中文字符编码格式介绍及相互转换 - Qsir的专栏 - 优快云博客  https://blog.youkuaiyun.com/Qsir/article/details/78425199

 

att1.add_header('Content-Disposition', 'attachment',filename=fn_string)

 

百度:python 邮箱地址 乱码

python 邮箱地址 乱码_百度搜索  https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=99140155_hao_pg&wd=python%20%E9%82%AE%E7%AE%B1%E5%9C%B0%E5%9D%80%20%E4%B9%B1%E7%A0%81&oq=python%2520%25E7%25BC%2596%25E7%25A0%2581%25E8%25A7%2584%25E8%258C%2583&rsv_pq=d97d247b00008371&rsv_t=6b3eFtU1FIkK3u%2Fbqm2p1xzR7bLoCxt3edGGics7iQyKie9%2FK3P06KR%2FrQ%2BhQUM%2BD2D9phoW&rqlang=cn&rsv_enter=1&inputT=35557&rsv_sug3=27&rsv_sug1=13&rsv_sug7=100&rsv_n=2&rsv_sug2=0&rsv_sug4=37195

Python使用email模块对邮件进行编码和解码的实例教程_python_脚本之家  https://www.jb51.net/article/87784.htm

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值