[代码] [Python]代码

#coding=utf-8
#easy send email, only can send plain text

import smtplib, mimetypes
from email.mime.text import MIMEText
from email.MIMEMultipart  import MIMEMultipart 
from smtplib import SMTPHeloError, SMTPAuthenticationError, SMTPHeloError, SMTPSenderRefused
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
from email.mime.base import MIMEBase
from email import encoders

server = 'smtp.qq.com'
from_addr = 'Purkylin<orighost@qq.com>'
user = 'xxxxxx'
pwd  = 'xxxxxx'

#easy send email, can only send plain text
def sendmail(target, subject, content) :
	msg  = MIMEText(content)
	# msg = MIMEText(content,'html','utf8') #这是正确显示Html中文的设置,会解析html标签,不再是原始文本。  
	# msg.set_charset('utf8') #这是正确显示中文的设置  
	to_addr   = target

	#this from_addr and to_addr is the content displayed in client, not affect on sending
	msg['Subject'] = subject
	msg['From'] = from_addr		
	if type(target)	== 'list':
		msg['To'] = ';'.join(target)
	else:
		msg['To'] = target

	try:
		s = smtplib.SMTP(server)
		s.login(user, pwd) 
		s.sendmail(from_addr, to_addr, msg.as_string())
	except SMTPHeloError:
		print 'Error: Can not connect server.'
		return 1
	except SMTPAuthenticationError:
		print 'Error: Username or password is not correct.'
		return 1
	except SMTPHeloError:
		print 'Error: Can not deliver to target host.'
		return 1
	except SMTPSenderRefused:
		print 'Error: The target server don\'t accept you from_addr'
		return 1
	except:
		print "Send failed"
		return 1
	finally:
		s.quit()

	print "Send success."
	return 0

def sendhtml(target, subject, html):
	to_addr = target
	msg = MIMEMultipart('alternative')
	msg['Subject'] = subject
	msg['From'] = from_addr	
	if type(target)	== 'list':
		msg['To'] = ';'.join(target)
	else:
		msg['To'] = target

	html = """\
		<html>
		  <head></head>
		  <body>
		    <p>Hi!<br>
		       How are you?<br>
		       Here is the <a href="http://www.python.org">link</a> you wanted.
		    </p>
		  </body>
		</html>
		"""

	msg = MIMEText(html, 'html')
	msg.attach(msg)

	try:
		s = smtplib.SMTP('smtp.qq.com')
		s.login(user, pwd) 
		s.sendmail(from_addr, target, msg.as_string())
	except SMTPHeloError:
		print 'Error: Can not connect server.'
		return 1
	except SMTPAuthenticationError:
		print 'Error: Username or password is not correct.'
		return 1
	except SMTPHeloError:
		print 'Error: Can not deliver to target host.'
		return 1
	except SMTPSenderRefused:
		print 'Error: The target server don\'t accept you from_addr'
		return 1
	except:
		print "Send failed"
		return 1
	finally:
		s.quit()

	print "Send success."
	return 0
	

# easy version
def sendeasy(target, subject, content, attach=[]):
	to_addr = target
	msg = MIMEMultipart()
	msg['Subject'] = subject
	msg['From'] = 'Purkylin<orighost@qq.com>'
	if type(target)	== 'list':
		msg['To'] = ';'.join(target)
	else:
		msg['To'] = target

	text = MIMEText(content)
	msg.attach(text)

	for fname in attach:
		fp = open(fname, 'rb')
		if fp == None:
			continue

		msg = MIMEApplication(fp.read())
		fp.close()
		msg.add_header('Content-Disposition', 'attachment', filename=fname)
		msg.attach(msg)

	msg.attach(text)
	
	try:
		s = smtplib.SMTP('smtp.qq.com')
		s.login(user, pwd) 
		s.sendmail(from_addr, target, msg.as_string())
	except SMTPHeloError:
		print 'Error: Can not connect server.'
		return 1
	except SMTPAuthenticationError:
		print 'Error: Username or password is not correct.'
		return 1
	except SMTPHeloError:
		print 'Error: Can not deliver to target host.'
		return 1
	except SMTPSenderRefused:
		print 'Error: The target server don\'t accept you from_addr'
		return 1
	except:
		print "Send failed"
		return 1
	finally:
		s.quit()

	print "Send success."
	return 0
	

#complex version
def sendcomp(target, subject, content, attach=[]):
	to_addr = target
	msg = MIMEMultipart()
	msg['Subject'] = subject
	msg['From'] = 'Purkylin<orighost@qq.com>'	
	if type(target)	== 'list':
		msg['To'] = ';'.join(target)
	else:
		msg['To'] = target

	text = MIMEText(content)
	msg.attach(text)

	for fname in attach:
		ctype, encoding = mimetypes.guess_type(fname)
		if ctype is None or encoding is not None:
			ctype = 'application/octet-stream'
            # No guess could be made, or the file is encoded (compressed), so
            # use a generic bag-of-bits type.

		maintype, subtype = ctype.split('/', 1)

		print maintype, subtype
		if maintype == 'text':
			fp = open(fname)
			#Note: we should handle calculating the charset
			msg = MIMEText(fp.read(), _subtype=subtype)
			fp.close()
		elif maintype == 'image':
			fp = open(fname, 'rb')
			msg = MIMEImage(fp.read(), _subtype=subtype)
			fp.close()
		elif maintype == 'audio':
			fp = open(fname, 'rb')
			msg = MIMEAudio(fp.read(), _subtype=subtype)
			fp.close()
		else:
			fp = open(fname, 'rb')
			msg = MIMEBase(maintype, subtype)
			msg.set_payload(fp.read())
			fp.close()
			# Encode the payload using Base64
			encoders.encode_base64(msg)

		msg.add_header('Content-Disposition', 'attachment', filename=fname)
		msg.attach(msg)

	msg.attach(text)

	try:
		s = smtplib.SMTP(server)
		s.login(user, pwd) 
		s.sendmail(from_addr, target, msg.as_string())
	except SMTPHeloError:
		print 'Error: Can not connect server.'
		return 1
	except SMTPAuthenticationError:
		print 'Error: Username or password is not correct.'
		return 1
	except SMTPHeloError:
		print 'Error: Can not deliver to target host.'
		return 1
	except SMTPSenderRefused:
		print 'Error: The target server don\'t accept you from_addr'
		return 1
	except:
		print "Send failed"
		return 1
	finally:
		s.quit()

	print "Send success."
	return 0


if __name__ == "__main__":
	#sendmail("orighost@qq.com", "你好", "welcome to use it to send emails.中文测试")
	sendeasy(['orighost@qq.com'], 'hello', 'very good', ['test.7z', 'test.jpg'])