当前访客身份:游客 [ 登录 | 加入 OSCHINA ]

代码分享

当前位置:
代码分享 » Python  » 网络编程
pengyouya123

发邮件(全功能)

pengyouya123 发布于 2013年11月01日 15时, 4评/1173阅
分享到: 
收藏 +0
3
<无详细内容>
标签: Python

代码片段(1) [全屏查看所有代码]

1. [代码][Python]代码     跳至 [1] [全屏预览]

#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'])
	


开源中国-程序员在线工具:Git代码托管 API文档大全(120+) JS在线编辑演示 二维码 更多»

发表评论 回到顶部 网友评论(4)

  • 1楼:此号作废 发表于 2013-11-01 16:07 回复此评论
    可以发附件不
  • 2楼:lazyphp 发表于 2013-11-01 17:02 回复此评论
    过不了多久,撸住就会加薪升职,出任总经理当上CEO,迎娶白富美,走向人生的巅峰。现在想想,撸住还是蛮激动的。
  • 3楼:pengyouya123 发表于 2013-11-01 17:24 回复此评论

    引用来自“小猫嘿嘿哈”的评论

    可以发附件不
    当然,你看接口就知道了
  • 4楼:Unika 发表于 2013-11-07 21:04 回复此评论
    似乎不能用
开源从代码分享开始 分享代码
pengyouya123的其它代码 全部(6)...