1 ##############################################################################
2 # Copyright (c) 2015 Huawei Technologies Co.,Ltd and others.
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
13 from email.mime.application import MIMEApplication
14 from email.mime.text import MIMEText
15 from email.mime.multipart import MIMEMultipart
17 LOG = logging.getLogger(__name__)
24 def __init__(self, srv=SRV, user=USER, passwd=PASSWD):
28 self._msg = MIMEMultipart('mixed')
35 self.__addr_choice = [self.TO, self.FROM, self.CC, self.BCC]
40 self.__mode = [self.HTML, self.PLAIN]
41 # self._charset = 'gb2312'
46 def attach_addr(self, addr, addr_type):
48 :param addr: a list of email address.
49 :param addr_type: must be one of [to, from, cc, bcc]
51 if not addr or not isinstance(addr, list):
52 LOG.error("The addr must be a list")
55 if addr_type not in self.__addr_choice:
56 LOG.error("Not support addr type")
59 if not self._msg[addr_type]:
60 self._msg[addr_type] = ','.join(addr)
61 self._msg[addr_type].join(addr)
63 def attach_title(self, title):
65 each time attach title, the old title will be covered.
68 self._msg["Subject"] = str(title)
70 def attach_text(self, text, mode):
71 if mode not in self.__mode:
72 LOG.error("The text mode not support.")
75 msg_alternative = MIMEMultipart('alternative')
76 msg_text = MIMEText(text, mode)
77 msg_alternative.attach(msg_text)
79 return self._msg.attach(msg_alternative)
81 def attach_files(self, files):
83 part = MIMEApplication(open(_file, "rb").read())
84 part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(_file))
85 self._msg.attach(part)
88 server = smtplib.SMTP(self.srv, timeout=self.timeout)
93 server.login(self.user, self.passwd)
95 if self._msg[self.TO]:
96 maillist += self._msg[self.TO].split(',')
97 if self._msg[self.CC]:
98 maillist += self._msg[self.CC].split(',')
99 if self._msg[self.BCC]:
100 maillist += self._msg[self.BCC].split(',')
101 ret = server.sendmail(self._msg[self.FROM].split(','),
102 maillist, self._msg.as_string())
103 LOG.info("send mail ret:%s", ret)
107 if __name__ == "__main__":
109 m.attach_addr(["vstf_server@vstf.com"], m.FROM)
110 m.attach_addr(["test@test.com"], m.TO)
124 m.attach_text(context, m.HTML)
125 m.attach_title("Email from xeson Check")