4 from email.mime.application import MIMEApplication
5 from email.mime.text import MIMEText
6 from email.mime.multipart import MIMEMultipart
8 LOG = logging.getLogger(__name__)
15 def __init__(self, srv=SRV, user=USER, passwd=PASSWD):
19 self._msg = MIMEMultipart('mixed')
26 self.__addr_choice = [self.TO, self.FROM, self.CC, self.BCC]
31 self.__mode = [self.HTML, self.PLAIN]
32 # self._charset = 'gb2312'
37 def attach_addr(self, addr, addr_type):
39 :param addr: a list of email address.
40 :param addr_type: must be one of [to, from, cc, bcc]
42 if not addr or not isinstance(addr, list):
43 LOG.error("The addr must be a list")
46 if addr_type not in self.__addr_choice:
47 LOG.error("Not support addr type")
50 if not self._msg[addr_type]:
51 self._msg[addr_type] = ','.join(addr)
52 self._msg[addr_type].join(addr)
54 def attach_title(self, title):
56 each time attach title, the old title will be covered.
59 self._msg["Subject"] = str(title)
61 def attach_text(self, text, mode):
62 if mode not in self.__mode:
63 LOG.error("The text mode not support.")
66 msg_alternative = MIMEMultipart('alternative')
67 msg_text = MIMEText(text, mode)
68 msg_alternative.attach(msg_text)
70 return self._msg.attach(msg_alternative)
72 def attach_files(self, files):
74 part = MIMEApplication(open(_file, "rb").read())
75 part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(_file))
76 self._msg.attach(part)
79 server = smtplib.SMTP(self.srv, timeout=self.timeout)
84 server.login(self.user, self.passwd)
86 if self._msg[self.TO]:
87 maillist += self._msg[self.TO].split(',')
88 if self._msg[self.CC]:
89 maillist += self._msg[self.CC].split(',')
90 if self._msg[self.BCC]:
91 maillist += self._msg[self.BCC].split(',')
92 ret = server.sendmail(self._msg[self.FROM].split(','),
93 maillist, self._msg.as_string())
94 LOG.info("send mail ret:%s", ret)
98 if __name__ == "__main__":
100 m.attach_addr(["vstf_server@vstf.com"], m.FROM)
101 m.attach_addr(["wangli11@huawei.com"], m.TO)
115 m.attach_text(context, m.HTML)
116 m.attach_title("Email from xeson Check")