文章笔记参考:Python教程
一、电子邮件的发件过程:
from_addr = input('From: ') password = input('Password: ') to_addr = input('To: ')
smtp_server = input('SMTP server') import smtplib server = smtplib.SMTP(smtp_server, 25) # the default protocol is 25 server.set_debuglevel(1) # 只是用来打印调试信息的,如果设置为0,就不打印 server.login(from_addr, password) # login SMTP
msg = MIMEText('hello world!', 'plain', 'utf-8') # 收件人可以有多个,所以这是一个list,msg是一个Message结构,所以转成string server.sendmail(from_addr, [to_addr], msg.as_string()) # 一定要退出服务器 server.quit()
from email import encoders from email.header import Header from email.mime.text import MIMEText from email.utils import parseaddr, formataddr import smtplib # 考虑到编码的原因,这里统一将name属性值改成utf-8,地址的话一定是统一的邮箱地址结构,所以不考虑 def __format_addr(s): name, addr = parseaddr(s) return formataddr((Header(name, 'utf-8').encode(), addr)) # 一些基本信息的定义 from_addr = input('From:') password = input('Password:') to_addr = input('To: ') smtp_server = input('SMTP server: ') # 纯文本邮件定义 msg = MIMEText('hello world!', 'plain', 'utf-8') # 定义发送人,接收人,以及描述信息(主题) msg['From'] = __format_addr('Your Dady: <%s>' % from_addr) msg['To'] = __format_addr('To son: <%s>' % to_addr) msg['Subject'] = Header('A how are you from SMTP......', 'utf-8').encode() print(msg) # 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()
from email import encoders from email.header import Header from email.mime.text import MIMEText from email.utils import parseaddr, formataddr import smtplib #字符集转换 def __format_addr(s): name, addr = parseaddr(s) return formataddr((Header(name, 'utf-8').decode(), addr)) #基本信息初始化 from_addr = input('From: ') password = input('Password: ') to_addr = input('To: ') #使用MIMEMultipart定义Message msg = MIMEMultipart() #初始化头 msg['From'] = __format_addr('Your Dady: <%s>' % from_addr) msg['To'] = __format_addr('Son: <%s>' % to_addr) msg['Subject'] = Header('A how are you from......').encode() #将文本内容添加入邮件 msg.attach(MIMEText('Send with file......', 'plain', 'utf-8')) #打开一个图片文件,将其添加到邮件中 with open('/Users/zhouming/Desktop/tupian.png', 'rb') as f: mime = MIMEBase('image', 'png', filename = 'tupian.png') #添加头部信息 mime.add_header('Content-Disposition', 'attachment', filename = 'tupian.png') mime.add_header('Content-ID', '<0>') mime.add_header('X-Attachment-Id', '0') #读取信息,默认字符集为空,这里是图片就不用设置了 mime.set_payload(f.read()) #使用Base64对图片编码 encoders.encode_base64(mime) msg.attach(mime)
set_payload(payload, charset=None)
Set the entire message object’s payload to payload. It is the client’s responsibility to ensure the payload invariants. Optional charset sets the message’s default character set; see set_charset() for details.
msg.attach(MIMEText('<html><body><h1>Hello</h1>' + '<p><img src="cid:0"></p>' + '</body></html>', 'html', 'utf-8'))
smtp_server = 'smtp.gmail.com' smtp_port = 587 server = smtplib.SMTP(smtp_server, smtp_port) server.starttls() # 剩下的代码和前面的一模一样: server.set_debuglevel(1) ...
import poplib from email.parser import Parser from email.header import decode_header from email.utils import parseaddr email = input('Email:') password = input('Password: ') pop3_server = input('POP3 server: ') pop3_server = 'pop.sina.com' #这是检测编码部分,有点不懂 def guess_charset(msg): charset = msg.get_charset() if charset is None: content_type = msg.get('Content-type', '').lower() pos = content_type.find('charset=') if pos >= 0: charset = content_type[pos + 8:].strip() return charset #这里只取出第一发件人 def decode_str(s): value, charset = decode_header(s)[0] if charset: value = value.decode(charset) return value #递归打印信息 def print_info(msg, indent = 0): if indent == 0: for header in ['From', 'To', 'Subject']: value = msg.get(header, '') if value: if header == 'Subject': value = decode_str(value) else: hdr, addr = parseaddr(value) name = decode_str(hdr) value = u'%s <%s>' % (name, addr) print('%s%s: %s' % (' ' * indent, header, value)) if (msg.is_multipart()): parts = msg.get_payload() for n, part in enumerate(parts): print('%spart %s' % (' '*indent, n)) print('%s--------------------' % (' '*indent)) print_info(part, indent + 1) else: content_type = msg.get_content_type() if content_type == 'text/plain' or content_type == 'text/html': content = msg.get_payload(decode = True) charset = guess_charset(msg) if charset: content = content.decode(charset) print('%sText: %s' % (' '*indent, content + '...')) else: print('%sAttachment: %s' % (' '*indent, content_type)) #下载原始邮件 server = poplib.POP3(pop3_server) server.set_debuglevel(0) print(server.getwelcome().decode('utf-8')) server.user(email) server.pass_(password) #打印邮件数量和占用空间 print('Message: %s, Size: %s' % server.stat()) resp, mails, octets = server.list() print(mails) #解析邮件 index = len(mails) resp, lines, octets = server.retr(index) msg_content = b'\r\n'.join(lines).decode('utf-8') msg = Parser().parsestr(msg_content) print_info(msg) server.quit()