python 邮件(一)

Posted by
import smtplib

①连接对象服务器(设连接对象为smtp)

smtp = smtplib.SMTP_SSL(服务器地址,服务器端口)

服务器地址必填,服务器端口选填

②登录前进行用户验证

smtp.ehlo(服务器地址)

③登录邮箱

smtp.login(邮箱账号,密码或者授权码)

④发送邮件

smtp.sendmail(发送邮箱,接收邮箱,邮箱对象.as_string())

⑤退出

smtp.quite()

from email.mine.multipart import MINEMultipart
from email.mine.text import MINEText
from email.header import Header

①添加文字内容:(设邮箱对象为msg)

msg = MINEText(内容,类型,编码方式)

其中类型分为两种:

Ⅰ.plain:简单的文字内容

Ⅱ.html:超文本

编码方式通常选择:utf-8

②设置邮箱主题:

msg['Subject'] = Header(标题,编码方式)

③设置邮箱发送者:

msg['From'] = 发送邮箱

④设置邮箱接收者:

msg['To'] = '接收者1;接收者2;......'

实例:

from email.mine import MINEText
from smtplib import SMTP_SSL
from email.header import Header
smtp = SMTP_SSL('smtp.qq.com')
smtp.set_debuglevel(1)       #set_debuglevel()时用来调试的。参数值为1表示开启调试模式,参数为0则为关闭调试
smtp.ehlo('smtp.qq.com')
smtp.login('123456789','adfsfsdfdf')
msg = MIMEText('测试内容','plain','utf-8')
msg['Subject'] = Header('测试标题','utf-8')
msg['From'] = '123456789@qq.com'
msg['To'] = '987654321@qq.com'
smtp.sendmail('123456789@qq.com','987654321@qq.com',msg.as_string())
smtp.quite()