# -*- coding: utf-8 -*- from email import encoders from email.header import Header from email.mime.text import MIMEText from email.MIMEMultipart import MIMEMultipart from email.utils import parseaddr, formataddr import smtplib import getpass from_addr = raw_input('From: ')#输入发信地址 password = getpass.getpass('Password: ')#输入密码 to_addr = raw_input('To: ')#输入收信地址 email_title = raw_input('email title: ')#输入邮件标题 email_body = raw_input('email body: ')#输入邮件内容 msg = MIMEMultipart('alternative')#兼容Plain和html两种 msg.attach(MIMEText(email_body, 'html', 'gbk'))#第一个参数是邮件内容,第二个参数是类型Plain是普通,html是页面,第三个参数是字符编码 msg['To'] = to_addr msg['Subject'] = Header(email_title, 'gbk').encode()#邮件标题 try: server = smtplib.SMTP('smtp.'+from_addr.split('@')[1].split('.')[0]+'.com', 25)#smtp服务器名称 server.starttls()#加密SMTP server.set_debuglevel(1)#1打印出和SMTP服务器交互的所有信息;-1不会打印 server.login(from_addr, password)#来登录SMTP服务器 server.sendmail(from_addr, [to_addr], msg.as_string())#发邮件,由于可以群发所以收件人是列表;as_string是将MIMEText对象转化为string print "OK!!!" except SMTPException: print "Error: unable to send email!" finally: server.quit()#关闭