Python实例---发邮件

1、不带附件

  1)构造一个smtplib.SMTP对象

  2)连接(connect)SMTP服务器,认证(login)

  3)发送邮件(sendmail)

  4)断开连接(quit)

  

View Code
#encoding:utf-8

import sys
import os.path
import smtplib
import email

def sendTextMail(mailhost,sender,passwd,recipients,ccto = '',bccto = '',subject = '',message = '', messagefile = ''):

  try:
    #mailport=smtplib.SMTP(mailhost,25)
    #mailport.login(sender, passwd)
    mailport = smtplib.SMTP(mailhost)  
    #设定调试级别,依情况而定  
    mailport.set_debuglevel(1)  
    #mailport.connect(mailhost)  
    mailport.login(sender, passwd) 
  except:
    sys.stderr.write('Unable to connect to SMTP host "' + mailhost \
                      + '"!\nYou can try again later\n')
    return 0
    
  if(os.path.exists(messagefile) and os.path.isfile(messagefile)):
    with open(messagefile,'r') as f:
      message += f.read()
    
  fullmessage = 'From: ' + ' <' + sender + '> \n' +\
              'To: ' + recipients + '\n' +\
              'CC: '+ ccto + '\n' +\
              'Bcc: ' + bccto + '\n' +\
              'Subject: ' + subject + '\n' +\
              'Date: ' + email.Utils.formatdate() +'\n' +\
              '\n' +\
              message

  try:
    #mailport.set_debuglevel(1)
    allrecipients = recipients.split(',')
    if not ccto == '':
      allrecipients.extend(ccto.split(',')) 
    if not bccto == '':
      allrecipients.extend(bccto.split(',')) 
    #print allrecipients
    #allrecipients must be list type
    failed = mailport.sendmail(sender, allrecipients, fullmessage)
  except Exception as e:
    sys.stderr.write(repr(e))
    return 0
  finally:
    mailport.quit()
    
  return 1
if __name__ == '__main__':
    #sendTextMail('smtp.qq.com', 'xxx@qq.com', 'password', 'reciver@qq.com', subject='titleone', message="jdhsadajdhadkDKDHIADHDHADH")
    sendTextMail('smtp.163.com', 'xxx@163.com', 'password', 'reciver@qq.com', subject='titleone', message="jdhsadajdhadkDKDHIADHDHADH")

2、带附件

  1)构造MIMEMultipart对象做为根容器 
  2)构造MIMEText\MIMEAudio\MIMEImage对象做为邮件显示内容并附加到根容器 
    a. 读入文件内容并格式化 
    b. 设置附件头 
  3) 得到格式化后的完整文本 
  4) 用smtp发送邮件

#encoding:utf-8
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
import smtplib
import sys
import os.path

def sendTextMail(mailhost, sender, passwd, recipients, subject = '', filename= '', messageText = ''):
  try:
    mailport = smtplib.SMTP(mailhost)
    mailport.set_debuglevel(1)
    mailport.login(sender, passwd)

    mailport = smtplib.SMTP(mailhost)  
    #设定调试级别,依情况而定  
    mailport.set_debuglevel(1)  
    #mailport.connect(mailhost)  
    mailport.login(sender, passwd) 
  except:
    sys.stderr.write('Unable to connect to SMTP host "' + mailhost + '"!\nYou can try again later\n')
    return 0

  #注意:此处basename要转换为gb2312编码,否则中文会有乱码。  
  #      特别,此处的basename为unicode编码,所以可以用basename.encode('gb2312')  
  #      如果basename为utf-8编码,要用basename.decode('utf-8').encode('gb2312')  
  #创建带附件的实例
  msg = MIMEMultipart()
  #构造附件1
  att1 = MIMEText(open(filename, 'rb').read(), 'base64', 'utf-8')
  att1["Content-Type"] = 'application/octet-stream'
  att1["Content-Disposition"] = 'attachment; filename = 123.txt'
  msg.attach(att1)

  #构造附件2
  basename = os.path.basename("test.py")
  att2 = MIMEText(open(filename, 'rb').read(), 'base64', 'unicode')
  att2["Content-Type"] = 'application/octet-stream'
  att2["Content-Disposition"] = 'attachment; filename = %s' % basename.encode('gb2312')
  msg.attach(att2)

  #添加图片 
  image = MIMEImage(open(u'C:\\Users\\Administrator.F1H6GUEWH61CUKV\\Downloads\\121.jpg', 'rb+').read())     
  image.add_header('Content-ID', '<image1>')
  image["Content-Disposition"] = 'attachment; filename=1.jpg'    
  msg.attach(image) 
  #添加图片
  #image = MIMEText(open('C:\\Users\\Administrator.F1H6GUEWH61CUKV\\Downloads\\121.jpg', 'rb').read(), 'base64', 'utf-8')  
  #image["Content-Type"] = 'application/octet-stream'  
  #image["Content-Disposition"] = 'attachment; filename=1.jpg'  
  #msg.attach(image)
  #添加邮件内容
  text_msg = MIMEText(messageText, 'plain', 'utf-8') 
  msg.attach(text_msg)  
  msg['to'] = recipients
  msg['from'] = sender
  msg['subject'] = subject

  try:
    mailport.sendmail(msg['from'], msg['to'], msg.as_string())
  except Exception as e:
    sys.stderr.write(repr(e))

if __name__ == '__main__':
  #sendTextMail('smtp.qq.com', 'xxx@qq.com', 'password', 'reciver@qq.com', subject='titleone', message="jdhsadajdhadkDKDHIADHDHADH")
  sendTextMail('smtp.163.com', 'xxx@163.com', 'pasword', 'reciver@qq.com', subject='titleone', filename = 'test.py',messageText="测试邮件1")

 

 

问题:qq.smtp.com连接不上,原因没找到.....求助

转载于:https://www.cnblogs.com/nanlou/archive/2013/05/06/3063412.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值