python使用smtplib和email库发送邮件
国内很多服务器提供商都默认禁止了smtp默认的25端口服务,而启用465端口发送邮件
在smtplib库中直接调用SMTP_SSL就是默认使用465端口
示例代码如下:
def send_eamil(receiver): global msg sender = 'xxx@163.com' psd = 'xxx' #是授权密码不是邮箱登录密码 mail_host='smtp.163.com' subject='xxx' to_addrs=receiver.split(',') #创建带附件的实例 msg=MIMEMultipart() msg['Subject']=Header(subject,'utf-8') msg['from']=Header(sender,'utf-8') msg['To']=",".join(to_addrs) #多个收件人 #创建正文,把文本添加到msg类中 msg.attach(MIMEText('Push test','plain','utf-8')) print('set ok') # #构造附件 # file_path='文件路径' # att1=MIMEText(open(file_path,'rb').read(), # 'base64','utf-8') # #att1["Content-Type"]='application/octet-stream;name=%s'%Header(filename,'utf-8').encode('utf-8') #与下边功能一致 # #att1["Content-Disposition"]='attachment;file_name=%s'%Header('%s'%filename,'utf-8').encode('utf-8') #与下边功能一致 # att1.add_header('Content-Disposition', 'attachment', filename=名字随便起)#没有这三行会出现文件结尾变成bin现象 # att1.add_header('Content-ID', '<0>') # att1.add_header('X-Attachment-Id', '0') # msg.attach(att1)#将附件添加到类文件 try: smtp=SMTP_SSL(mail_host) smtp.set_debuglevel(1) #显示发送过程 # smtp.connect(mail_host) print('connect ok') smtp.login(sender,psd) smtp.sendmail(sender,to_addrs,msg.as_string()) smtp.quit() print('发送成功') except Exception as result: print('发送失败,异常为%s'%result) if __name__ == '__main__': # make_excel() send_eamil('xxx@xx.com')