Python实例 -- 收发邮件

本文提供了一段使用Python发送邮件的代码示例,并详细解释了如何通过SMTP连接到邮件服务器并登录,同时展示了接收邮件的基本流程。适用于Python初学者和希望了解邮件通信原理的开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python实例 -- 收发邮件 2012-09-12 20:17:49

分类: LINUX

python发邮件
  1. #!/usr/bin/env python3
  2. #coding: utf-8
  3. import smtplib
  4. from email.mime.text import MIMEText
  5. from email.header import Header
  6.   
  7. sender = '***'
  8. receiver = '***'
  9. subject = 'python email test'
  10. smtpserver = 'smtp.163.com'
  11. username = '***'
  12. password = '***'
  13.   
  14. msg = MIMEText('你好','plain','utf-8')#中文需参数‘utf-8’,单字节字符不需要
  15. msg['Subject'] = Header(subject, 'utf-8')
  16.   
  17. smtp = smtplib.SMTP()
  18. smtp.connect('smtp.163.com')
  19. smtp.login(username, password)
  20. smtp.sendmail(sender, receiver, msg.as_string())
  21. smtp.quit()

python收邮件
  1. #!/usr/bin/env python3 
  2. # -*- coding: utf-8 -*-
  3.       
  4.     import poplib
  5.     from email import parser
  6.       
  7.     host = 'pop.gmail.com'
  8.     username = 'mine@gmail.com'
  9.     password = '*******'
  10.       
  11.     pop_conn = poplib.POP3_SSL(host)
  12.     pop_conn.user(username)
  13.     pop_conn.pass_(password)
  14.       
  15.     #Get messages from server:
  16.     messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
  17.       
  18.     # Concat message pieces:
  19.     messages = ["\n".join(mssg[1]) for mssg in messages]
  20.       
  21.     #Parse message intom an email object:
  22.     messages = [parser.Parser().parsestr(mssg) for mssg in messages]
  23.     for message in messages:
  24.         print message['Subject']
  25.     pop_conn.quit()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值