python 发送带有附件的邮件

恩恩。。奇怪,刚才是用了另外一个账号发吗。。不管了反正都是新的。


来新公司实习,需要一个发邮件的小工具来给自己用。


之前没接触过python,百度结合领导给的参考代码总算写出来了。。


之前没写过博客,这次也就当做个笔记吧。。


import smtplib
import email.utils
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.MIMEBase import MIMEBase
from email import Encoders


import random
import os
import getpass
import time
# Prompt the user for connection info
def sendmail(to_email = '[email protected]',content='<br/>Test message from PyMOTW.<br/>',subject='Test from PyMOTW'):
    #raw_input('Recipient: ')
    servername = 'smtp.XXXXX.com'#raw_input('Mail server name: ')
    username = '[email protected]' #raw_input('Mail username: ')
    password = '123' #getpass.getpass("%s's password: " % username)
    # 添加附件,这个附件的名称是例如Show-2000-01-01.txt的
    date = time.strftime('%Y-%m-%d',time.localtime(time.time()))
    file = 'Show-'+date+'.txt'
    msg = MIMEMultipart()
    part = MIMEBase('application', "octet-stream")
    part.set_payload( open(file,"rb").read() )
    Encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename = %s'%file)
    msg.attach(part)
    msg.set_unixfrom('name')
    msg['To'] = email.utils.formataddr(('Recipient', to_email)) 
    #print  msg['To'],type(msg['To'])
    #input()
    msg['From'] = email.utils.formataddr(('name','[email protected]'))
    if not isinstance(subject,unicode):
        subject = unicode(subject)
    msg['Subject'] = subject
    server = smtplib.SMTP(servername,"25") 
    #print msg.as_string()
    #input() 
    try:
        server.set_debuglevel(True)
        # identify ourselves, prompting server for supported features
        server.ehlo()
        # If we can encrypt this session, do it if server.has_extn('STARTTLS'):
        server.starttls()
        server.ehlo() # reidentify ourselves over TLS connection
        server.login(username, password)


        server.sendmail('[email protected]', to_email.split(','),msg.as_string())
   


    except Exception as e:
        print e
    finally: 
        server.quit()


if __name__=='__main__':
    to=('[email protected]')
    sendmail(to_email = '[email protected]',content='test', subject='title')

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章