Last active
August 29, 2015 14:18
-
-
Save dongguosheng/5dceea8f2944247c42ca to your computer and use it in GitHub Desktop.
Send mail util with attachment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from email.mime.text import MIMEText | |
from email.mime.multipart import MIMEMultipart | |
import smtplib | |
class Message(object): | |
'''Email util.''' | |
def __init__(self, mailto_list=['xxxxxx@qq.com'], mail_host='smtp.126.com', | |
mail_user='yyyyyy', mail_password='zzzzzz', mail_postfix='126.com', attach_file_list=[]): | |
'''Initialize the Message util.''' | |
self.mailto_list = mailto_list | |
self.mail_host = mail_host | |
self.mail_user = mail_user | |
self.mail_password = mail_password | |
self.mail_postfix = mail_postfix | |
self.__subject = '' | |
self.__content = '' | |
self.attach_file_list = attach_file_list | |
self.server = smtplib.SMTP() | |
@property | |
def subject(self): | |
return self.__subject | |
@property | |
def content(self): | |
return self.__content | |
@subject.setter | |
def subject(self, subject): | |
self.__subject = subject | |
@content.setter | |
def content(self, content): | |
self.__content = content | |
def __load_attachments(self): | |
self.attach_list = [] | |
for filename in self.attach_file_list: | |
with open(filename, 'rb') as f: | |
att = MIMEText(f.read(), 'base64', 'gb2312') | |
att["Content-Type"] = 'application/octet-stream' | |
att["Content-Disposition"] = 'attachment; filename="' + filename + '"' | |
self.attach_list.append(att) | |
def send_mail(self): | |
'''Send mail.''' | |
self.msg = MIMEMultipart() | |
self.__load_attachments() | |
for att in self.attach_list: | |
msg.attach(att) | |
self.msg['Subject'] = self.__subject | |
self.msg['From'] = '<' + self.mail_user + '@' + self.mail_postfix + '>' | |
self.msg['To'] = ';'.join(self.mailto_list) | |
try: | |
self.server.connect(self.mail_host) | |
self.server.login(self.mail_user, self.mail_password) | |
self.server.sendmail(self.msg['From'], self.mailto_list, self.msg.as_string()) | |
self.server.close() | |
print 'email succeed.' | |
return True | |
except Exception, e: | |
print str(e) | |
print 'email failed.' | |
return False | |
def main(): | |
message = Message(mail_to_list=['dongguosheng179@163.com'], mail_host='smtp.163.com', mail_user='yyyyyy', mail_password='zzzzzz', mail_postfix='163.com', attach_file_list=['./test.txt']) | |
message.subject = 'Hello' | |
message.content = 'World.' | |
message.send_mail() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment