##发送普通txt文件(与发送html邮件不同的是邮件内容设置里的type设置为text,下面代码为发送普通邮件的另一种方法)
import smtplib
import string
from email.mime.text import MIMEText
from email.utils import formataddr
host = 'smtp.263.net' ##定义smtp主机
SUBJECT = "test smtplib" #定义邮件主题
TO = "xx@xx.com" ##邮件接收人
FROM = "xxxx@xx.com" ##邮件发送人
text = "content" #邮件内容
###拼接邮件主体内容
BODY = "\r\n".join(("From %s:" % FROM,"To: %s" % TO,"Subject:%s" % SUBJECT,"",text)).encode("utf-8")
server = smtplib.SMTP() #创建smtp对象
server.connect(host,"25") ##通过connect方法连接smtp主机
server.starttls() ##启动安全传输模式
server.login("xxx@huixxx.com",'GAxxx@xxx') ##邮箱账号登录
server.sendmail(FROM,[TO],BODY)
server.quit() ##断开smtp连接
发送html邮件
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
HOST = 'smtp.263.net' ##定义smtp主机
SUBJECT = "test smtplib" #定义邮件主题
TO = "xxx@xxx.com" ##邮件接收人(可以为一个列表)
FROM = "xxx@xxx.com" ##邮件发送人
text = "content" #邮件内容
def sendmail():
msg = MIMEText(content,_subtype='html',_charset='utf-8') ##邮件内容,content邮件内容,plain为邮件类型,charset为字符集
msg['From'] = FROM
msg['To'] = TO #如果此处为列表(';'.join(to_list))
msg['Subject'] = SUBJECT
server = smtplib.SMTP("smtp.263.net",25)
server.login("aa@aa.com.cn","xxxxx") #发送者的用户名和密码
server.sendmail(FROM,TO,msg.as_string())
server.quit()
sendmail()
发送带附件的邮件
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
#创建一个带附件的实例
msg = MIMEMultipart()
#构造附件1
file1 = MIMEText(open('d:\\123.rar', 'rb').read(), 'base64', 'utf-8')
file1["Content-Type"] = 'application/octet-stream'
file1["Content-Disposition"] = 'attachment; filename="123.doc"' #这里的filename可以任意写,写什么名字,邮件中显示什么名字
msg.attach(file1)
#加邮件头
msg['to'] = 'YYY@YYY.com'
msg['from'] = 'XXX@XXX.com'
msg['subject'] = 'hello world' #邮件主题
#发送邮件
server = smtplib.SMTP()
server.connect('smtp.XXX.com',"25")
server.login('XXX','XXXXX') #XXX为用户名,XXXXX为密码
server.sendmail(msg['from'], msg['to'],msg.as_string())
server.quit()
发送带图片的邮件
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
msg['From'] = "XXX@XXX.com" #邮件发件人
msg['To'] = "YYY@YYY.com" #邮件接收人
msg['Subject'] = "hello world" ##邮件主题
def addimg(img_src,imgid):
fp = open(img_src,'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Conteng-ID',imgid)
return msgImage ##返回msgImage对象
msg_text = MIMEText("""<table><tr><td><img src="cid:aa"></td></tr></table>""","html","utf-8")
#创建MIMEMultipart对象,采用related定义内嵌资源
msg = MIMEMultipart('related')
msg.attach(msg_text)
msg.attach(addimg("C:\aa.img",aa)) ##这里的aa要与msg_text里的aa对应
#发送邮件
server = smtplib.SMTP()
server.connect('smtp.XXX.com',"25")
server.starttls() ##启动安全传输模式
server.login('XXX','XXXXX') #XXX为用户名,XXXXX为密码
server.sendmail(msg['From'], msg['To'],msg.as_string()) #这里的前两个参数自定义
server.quit()