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__)
25 def __init__(self, srv=SRV, user=USER, passwd=PASSWD):
29 self._msg = MIMEMultipart('mixed')
36 self.__addr_choice = [self.TO, self.FROM, self.CC, self.BCC]
41 self.__mode = [self.HTML, self.PLAIN]
42 # self._charset = 'gb2312'
47 def attach_addr(self, addr, addr_type):
49 :param addr: a list of email address.
50 :param addr_type: must be one of [to, from, cc, bcc]
52 if not addr or not isinstance(addr, list):
53 LOG.error("The addr must be a list")
56 if addr_type not in self.__addr_choice:
57 LOG.error("Not support addr type")
60 if not self._msg[addr_type]:
61 self._msg[addr_type] = ','.join(addr)
62 self._msg[addr_type].join(addr)
64 def attach_title(self, title):
66 each time attach title, the old title will be covered.
69 self._msg["Subject"] = str(title)
71 def attach_text(self, text, mode):
72 if mode not in self.__mode:
73 LOG.error("The text mode not support.")
76 msg_alternative = MIMEMultipart('alternative')
77 msg_text = MIMEText(text, mode)
78 msg_alternative.attach(msg_text)
80 return self._msg.attach(msg_alternative)
82 def attach_files(self, files):
84 part = MIMEApplication(open(_file, "rb").read())
86 'Content-Disposition',
88 filename=os.path.basename(_file))
89 self._msg.attach(part)
92 server = smtplib.SMTP(self.srv, timeout=self.timeout)
97 server.login(self.user, self.passwd)
99 if self._msg[self.TO]:
100 maillist += self._msg[self.TO].split(',')
101 if self._msg[self.CC]:
102 maillist += self._msg[self.CC].split(',')
103 if self._msg[self.BCC]:
104 maillist += self._msg[self.BCC].split(',')
105 ret = server.sendmail(self._msg[self.FROM].split(','),
106 maillist, self._msg.as_string())
107 LOG.info("send mail ret:%s", ret)
111 if __name__ == "__main__":
113 m.attach_addr(["vstf_server@vstf.com"], m.FROM)
114 m.attach_addr(["test@test.com"], m.TO)
128 m.attach_text(context, m.HTML)
129 m.attach_title("Email from xeson Check")