254   Python

之前利用Python写了一个简单的邮件发送类,支持文本和附件;

记录下来方便以后使用

#!/usr/bin/python
class email:
		
	def send(self,subject,content,mailto,attachment='0'):

		import logging;
		import os,chardet,smtplib

		from email.mime.text import MIMEText
		from email.mime.multipart import MIMEMultipart
		from email.mime.application import MIMEApplication 
		from email.header import Header

		logging.basicConfig(filename='email.log',level=logging.DEBUG,format="%(asctime)s - %(name)s  - %(levelname)s - %(message)s");

		sender = '123456@qq.com'
		passwd = '123456'
		server = 'smtp.qq.com'
		fromer = '123456<123456@qq.com>'


		main_msg = MIMEMultipart();
		main_msg['Subject'] = Header(subject, 'utf-8')
		main_msg["From"] = fromer;
		text_msg = MIMEText(content,'plain','utf-8');
		main_msg.attach(text_msg);

		main_msg["To"] = mailto;

		if attachment != '0':
			att = MIMEApplication(open(attachment, 'rb').read());
			att["Content-Disposition"] = 'attachment; filename=%s' % (attachment);
			main_msg.attach(att);

		try:
			smtp = smtplib.SMTP(server)
			smtp.ehlo()
			smtp.login(sender, passwd)
			smtp.sendmail(sender, mailto, main_msg.as_string())
			smtp.quit()
			logging.info('Send email successfully')
		except Exception ,e:
			logging.exception('ERROR')
			print e
			sys.exit(1)

 



email = email();

email.send('test','Hello','123456@qq.com','test.py');



Leave a Reply

Your email address will not be published. Required fields are marked *