def send_text_and_attachment_email(self, from_address, to_addresses, subject, message, attachment_text, attachment_filename='patch.diff'): """Send a Unicode message and an 8-bit attachment. See create_email for common parameter definitions. :param attachment_text: This is assumed to be an 8-bit text attachment. This assumes you want the attachment to be shown in the email. So don't use this for binary file attachments. :param attachment_filename: The name for the attachement. This will give a default name for email programs to save the attachment. """ msg, from_email, to_emails = self.create_email(from_address, to_addresses, subject, message) # Must be an 8-bit string assert isinstance(attachment_text, str) diff_payload = MIMEText(attachment_text, 'plain', '8-bit') # Override Content-Type so that we can include the name content_type = diff_payload['Content-Type'] content_type += '; name="%s"' % (attachment_filename, ) diff_payload.replace_header('Content-Type', content_type) diff_payload['Content-Disposition'] = ('inline; filename="%s"' % (attachment_filename, )) msg.attach(diff_payload) self.send_email(msg, from_email, to_emails)
def BuildReviewEmail(strReviewHTML, strReviewText, objReview, strFromAddress, strFromName, strToAddress, blnIncludeAmazonCoUk, blnIncludeAmazonCom): dictImages = {'DropSmall3.jpg':'DropSmall3', 'BooksForCoaches4.gif':'BooksForCoaches'} objEmail = MIMEMultipart('related') objEmail['Subject'] = objReview.BookTitle objEmail['From'] = '"%s" <%s>' % (strFromName, strFromAddress) objEmail['To'] = strToAddress objMessage = MIMEMultipart('alternative') objHTMLMessage = MIMEText(strReviewHTML, 'html') objHTMLMessage.replace_header('Content-Transfer-Encoding', 'quoted-printable') objTextMessage = MIMEText(strReviewText) objMessage.attach(objHTMLMessage) objMessage.attach(objTextMessage) objEmail.attach(objMessage) for strFullName in dictImages.keys(): objEmail.attach(GetImage(strFullName, dictImages[strFullName])) if blnIncludeAmazonCoUk: objEmail.attach(GetImage("AmazonCoUk.gif", "AmazonCoUk")) if blnIncludeAmazonCom: objEmail.attach(GetImage("AmazonCom.gif", "AmazonCom")) return objEmail
def send_text_and_attachment_email(self, from_address, to_addresses, subject, message, attachment_text, attachment_filename='patch.diff'): """Send a Unicode message and an 8-bit attachment. See create_email for common parameter definitions. :param attachment_text: This is assumed to be an 8-bit text attachment. This assumes you want the attachment to be shown in the email. So don't use this for binary file attachments. :param attachment_filename: The name for the attachement. This will give a default name for email programs to save the attachment. """ msg, from_email, to_emails = self.create_email(from_address, to_addresses, subject, message) # Must be an 8-bit string assert isinstance(attachment_text, str) diff_payload = MIMEText(attachment_text, 'plain', '8-bit') # Override Content-Type so that we can include the name content_type = diff_payload['Content-Type'] content_type += '; name="%s"' % (attachment_filename,) diff_payload.replace_header('Content-Type', content_type) diff_payload['Content-Disposition'] = ('inline; filename="%s"' % (attachment_filename,)) msg.attach(diff_payload) self.send_email(msg, from_email, to_emails)
def encode_email_part(content, content_type): try: # simplest email - plain ascii encoded_content = content.encode('ascii') encoding = 'ascii' except Exception: # utf8 will get base64 encoded so we only do it if ascii fails encoded_content = content.encode('utf-8') encoding = 'utf-8' for line in encoded_content.splitlines(): if len(line) > MAX_MAIL_LINE_OCTETS: # switch to Quoted-Printable encoding to avoid too-long lines # we could always Quoted-Printabl, but it makes the output a little messier and less human-readable # the particular order of all these operations seems to be very important for everything to end up right msg = MIMEText(None, content_type) msg.replace_header('content-transfer-encoding', 'quoted-printable') cs = email.charset.Charset('utf-8') cs.header_encoding = email.charset.QP cs.body_encoding = email.charset.QP payload = cs.body_encode(content.encode('utf-8')) msg.set_payload(payload, 'utf-8') return msg else: return MIMEText(encoded_content, content_type, encoding)
def SendPrettyEmail(strEmailAddress, strMessage, strSubject, objHere, strTextMessage=""): strFromAddress = "*****@*****.**" strFromName = "Coen de Groot" strHTMLTemplate = objHere.restrictedTraverse("/MCI/Templates/GeneralMessageHTML").data + "" strTextTemplate = objHere.restrictedTraverse("/MCI/Templates/GeneralMessageText").data + "" strHTMLBody = strHTMLTemplate % strMessage if strTextMessage: strTextBody = strTextMessage else: strTextBody = strTextTemplate % GeneralFunctions.HTMLToText(strMessage) objEmail = MIMEMultipart('related') objEmail['Subject'] = strSubject objEmail['From'] = '"%s" <%s>' % (strFromName, strFromAddress) objEmail['To'] = strEmailAddress objMessage = MIMEMultipart('alternative') objHTMLMessage = MIMEText(strHTMLBody, 'html') objHTMLMessage.replace_header('Content-Transfer-Encoding', 'quoted-printable') objTextMessage = MIMEText(strTextBody) objMessage.attach(objHTMLMessage) objMessage.attach(objTextMessage) objEmail.attach(objMessage) objEmail.attach(GetImage('DropSmall3.jpg', 'DropSmall3')) SendNiceEmail(objEmail, strFromAddress, strFromName, strEmailAddress)
def main(argv): is_looping = False root_path = "./" move_path = None fail_path = DEFAULT_FAIL_PATH try: opts, args = getopt.getopt(argv, "i:o:f:l") except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt == "-i": root_path += arg elif opt == "-o": move_path = "./" + arg elif opt == "-f": fail_path = "./" + arg elif opt == "-l": is_looping = True msg = "Importer naturally stopped." logger.info("Importer started with input=" + root_path + ", output=" + str(move_path) + ", fail=" + fail_path + ", loop=" + str(is_looping)) try: while True: print "Importing..." parser_findzip(root_path, move_path, fail_path, is_looping) if (False == is_looping): break print "Waiting..." time.sleep(10) except: msg = traceback.format_exc() print msg if (False == is_looping): return logger.info("Mailing...") mail_obj = MIMEMultipart() mail_obj['Subject'] = EMAIL_SUBJECT mail_obj['From'] = EMAIL_FROM mail_obj['To'] = listToStr(EMAIL_RECEIVERS) mail_obj.preamble = "This is a multi-part message in MIME format." mail_obj.epilogue = '' msg_txt = MIMEText(msg) msg_txt.replace_header('Content-Type', 'text/html; charset="big5"') mail_obj.attach(msg_txt) msg_body = mail_obj.as_string() smtpObj = smtplib.SMTP('relay-b.pegatroncorp.com') smtpObj.sendmail(EMAIL_FROM, EMAIL_RECEIVERS, msg_body) smtpObj.quit()
def _html(self): """ # 发送一个包含纯文本、html和附件邮件: # 发送成功少纯文本的内容,代码没有报错,把其他的代码注掉仅发送纯文本内容,纯文本中的内容在邮件中是能看到的。 """ # mul Header self.message['Message-Id'] = Header(self._makeMsgId(), self.character) if self.reply_to: self.message['Reply-to'] = Header(self.reply_to, self.character) try: self.message['Subject'] = Header(self.subject, self.character) except BaseException as e: self.message['Subject'] = Header('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', self.character) self.message['From'] = Header(self.mail_from, self.character) self.message['To'] = Header(self.mail_to, self.character) self.message["Date"] = formatdate(localtime=True) if self.is_need_receipt: self.message['Disposition-Notification-To'] = Header(self.mail_from, self.character) if self.edm_check_result: self.message['Edm-Check-Result'] = Header(self.edm_check_result, self.character) # mul Content(html或纯文本) if self.text_content: if self.encoding == "base64": mt = MIMEText(self.text_content, 'plain', self.character) else: mt = MIMEText(None, _subtype="plain") mt.replace_header('content-transfer-encoding', self.encoding) mt.set_payload(self.text_content.encode(self.character).encode('quoted-printable'), self.character) self.message.attach(mt) if self.content: if self.encoding == "base64": mt = MIMEText(self.content, 'html', self.character) else: mt = MIMEText(None, _subtype="html") mt.replace_header('content-transfer-encoding', self.encoding) mt.set_payload(self.content.encode(self.character).encode('quoted-printable'), self.character) self.message.attach(mt) # mul Attachment(附件,传统附件解析) for filepath, filetype, filename in self.attachment: try: real_filepath = os.path.join(self.attachment_path, str(self.template_id), filepath.encode('utf-8')) attachment = MIMEText(open(real_filepath, 'r').read(), self.encoding, self.character) attachment['Content-Type'] = filetype attachment['Content-Disposition'] = 'attachment;filename="%s"' % Header(filename, self.character) self.message.attach(attachment) except BaseException as e: print e continue return self.message.as_string()
def notify_mail(msg): mail_obj = MIMEMultipart() mail_obj['Subject'] = EMAIL_SUBJECT mail_obj['From'] = private.mail_from_addr mail_obj['To'] = listToStr(private.get_mail_list()) mail_obj.preamble = "This is a multi-part message in MIME format." mail_obj.epilogue = '' msg_txt = MIMEText(msg.replace("\n", "<br>")) msg_txt.replace_header('Content-Type', 'text/html; charset="big5"') mail_obj.attach(msg_txt) msg_body = mail_obj.as_string() smtpObj = smtplib.SMTP(private.mail_server_addr) smtpObj.sendmail(private.mail_from_addr, private.get_mail_list(), msg_body) smtpObj.quit()
def notify_mail(project, tsp): msg = "FACTORY ALERT!!! Project: %s, TSP: %s" % (project, tsp) print msg mail_obj = MIMEMultipart() mail_obj['Subject'] = EMAIL_SUBJECT mail_obj['From'] = EMAIL_FROM mail_obj['To'] = listToStr(EMAIL_RECEIVERS) mail_obj.preamble = "This is a multi-part message in MIME format." mail_obj.epilogue = '' msg_txt = MIMEText(msg) msg_txt.replace_header('Content-Type', 'text/html; charset="big5"') mail_obj.attach(msg_txt) msg_body = mail_obj.as_string() smtpObj = smtplib.SMTP('relay-b.pegatroncorp.com') smtpObj.sendmail(EMAIL_FROM, EMAIL_RECEIVERS, msg_body) smtpObj.quit()
def generate_body(self): #创建纯文本 if self.messagetext: body_plain = MIMEText(self.messagetext, _subtype = 'plain', _charset = 'UTF-8') if body_plain: self.attach.attach(body_plain) #创建超文本 if self.messagehtml: body_html = MIMEText(self.messagehtml, _subtype = 'html', _charset = 'UTF-8') if body_html: self.attach.attach(body_html) #创建附件 for filename in self.filelist: onlyfilename = os.path.basename(filename) loginfo('type:', type(onlyfilename)) onlyfilename = '=?utf-8?b?%s?=' % (base64.b64encode(onlyfilename.encode('utf-8'))) loginfo('onlyfilename:', onlyfilename) attachment = MIMEText(Encoders._bencode(open(filename, 'rb').read())) attachment.replace_header('Content-type', 'Application/octet-stream: name="' + onlyfilename + '"') attachment.replace_header('Content-Transfer-Encoding', 'base64') attachment.add_header('Content-Disposition', 'attachment;filename="' + onlyfilename + '"') self.attach.attach(attachment)
mail_msg_str += """<br/>""" mail_msg_str += mail_msg_tail mail_obj = MIMEMultipart() mail_obj['Subject'] = subject mail_obj['From'] = from_addr if os.getenv("cm_fetch_code_ok") == "y": mail_obj['To'] = COMMASPACE.join(to_addr_success) else: mail_obj['To'] = COMMASPACE.join(to_addr_fail) #msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s" % (from_addr, to_addr,subject, msg_txt) msg_content = MIMEText(mail_msg_str) msg_content.replace_header('Content-Type', 'text/html; charset="big5"') mail_obj.attach(msg_content) s = smtplib.SMTP('10.113.2.107') s.set_debuglevel(0); __SendMailResult = "%04d/%02d/%02d %02d:%02d:%02d\t\t" % (datetime.now().year, datetime.now().month, datetime.now().day, datetime.now().hour, datetime.now().minute, datetime.now().second) try: # smtp_server.sendmail(mail_from_addr, mail_to_addrs, mail_obj.as_string()) if os.getenv("cm_fetch_code_ok") == "y": s.sendmail(from_addr,to_addr_success,mail_obj.as_string()) else: s.sendmail(from_addr,to_addr_fail,mail_obj.as_string()) except smtplib.SMTPRecipientsRefused, e: __SendMailResult += "** Exception SMTPRecipientsRefused **", e
def main(argv): is_looping = False root_path = "./" move_path = None fail_path = DEFAULT_FAIL_PATH try: opts, args = getopt.getopt(argv, "i:o:f:l") except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt == "-i": root_path += arg elif opt == "-o": move_path = "./" + arg elif opt == "-f": fail_path = "./" + arg elif opt == "-l": is_looping = True msg = "Importer naturally stopped." logger.info( "Importer started with input=" + root_path + ", output=" + str(move_path) + ", fail=" + fail_path + ", loop=" + str(is_looping) ) try: while True: print "Importing..." parser_findzip(root_path, move_path, fail_path, is_looping) if False == is_looping: break print "Waiting..." time.sleep(10) except: msg = traceback.format_exc() print msg if False == is_looping: return logger.info("Mailing...") mail_obj = MIMEMultipart() mail_obj["Subject"] = EMAIL_SUBJECT mail_obj["From"] = EMAIL_FROM mail_obj["To"] = listToStr(EMAIL_RECEIVERS) mail_obj.preamble = "This is a multi-part message in MIME format." mail_obj.epilogue = "" msg_txt = MIMEText(msg) msg_txt.replace_header("Content-Type", 'text/html; charset="big5"') mail_obj.attach(msg_txt) msg_body = mail_obj.as_string() smtpObj = smtplib.SMTP("relay-b.pegatroncorp.com") smtpObj.sendmail(EMAIL_FROM, EMAIL_RECEIVERS, msg_body) smtpObj.quit()
def send(self): """ de: Sendet die Email an den Empfaenger. Wird das Email nur an einen Empfaenger gesendet, dann wird bei Erfolg <True> zurueck gegeben. Wird das Email an mehrere Empfaenger gesendet und wurde an mindestens einen der Empfaenger erfolgreich ausgeliefert, dann wird ebenfalls <True> zurueck gegeben. Wird das Email nur an einen Empfaenger gesendet, dann wird bei Misserfolg <False> zurueck gegeben. Wird das Email an mehrere Empfaenger gesendet und wurde an keinen der Empfaenger erfolgreich ausgeliefert, dann wird <False> zurueck gegeben. """ # # pruefen ob alle notwendigen Informationen angegeben wurden # if len(self.from_address.strip()) == 0: raise NoFromAddressException() if self.recipients.count() == 0: if (self.cc_recipients.count() == 0) and (self.bcc_recipients.count() == 0): raise NoToAddressException() if len(self.subject.strip()) == 0: raise NoSubjectException() # # Email zusammensetzen # if self.attachments.count() == 0: # Nur Text msg = MIMEText(_text=self.message, _subtype=self.content_subtype, _charset=self.content_charset) else: # Multipart msg = MIMEMultipart() if self.message: att = MIMEText(_text=self.message, _subtype=self.content_subtype, _charset=self.content_charset) msg.attach(att) if self.inline: msg.replace_header("Content-Type", "multipart/related") # Empfänger, CC, BCC, Absender, User-Agent, Antwort-an # und Betreff hinzufügen from_str = formataddr((self.from_caption, self.from_address)) msg["From"] = from_str if self.reply_to_address: reply_to_str = formataddr((self.reply_to_caption, self.reply_to_address)) msg["Reply-To"] = reply_to_str if self.recipients.count() > 0: msg["To"] = ", ".join(self.recipients.get_list()) if self.cc_recipients.count() > 0: msg["Cc"] = ", ".join(self.cc_recipients.get_list()) msg["Date"] = formatdate(time.time()) msg["User-Agent"] = self.user_agent try: msg["Subject"] = Header(self.subject, self.header_charset) except (UnicodeDecodeError): msg["Subject"] = Header(self.subject, self.content_charset) # User defined header_fields if self.header_fields: for key, value in self.header_fields.items(): msg[key] = value msg.preamble = "You will not see this in a MIME-aware mail reader.\n" msg.epilogue = "" # Falls MULTIPART --> zusammensetzen if self.attachments.count() > 0: for filetupel in self.attachments.get_list(): filename = filetupel[0] inline = filetupel[1] id = filetupel[2] # Pruefen ob Datei existiert if not os.path.isfile(filename): raise AttachmentNotFoundException(filename=filename) # Datentyp herausfinden ctype, encoding = mimetypes.guess_type(filename) if ctype is None or encoding is not None: ctype = "application/octet-stream" maintype, subtype = ctype.split("/", 1) if maintype == "text": fp = file(filename) # Note: we should handle calculating the charset att = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == "image": fp = file(filename, "rb") att = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == "audio": fp = file(filename, "rb") att = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = file(filename, "rb") att = MIMEBase(maintype, subtype) att.set_payload(fp.read()) fp.close() # Encode the payload using Base64 Encoders.encode_base64(att) # Set the filename parameter att.add_header("Content-Disposition", "attachment", filename=os.path.split(filename)[1].strip()) msg.attach(att) if inline: att.add_header("Content-ID", "<%s>" % (id,)) # # Am SMTP-Server anmelden # smtp = smtplib.SMTP() if self.smtp_server: smtp.connect(self.smtp_server) else: smtp.connect() # TLS-Verschlüsselung if self.use_tls: smtp.ehlo() smtp.starttls() smtp.ehlo() # authentifizieren if self.smtp_user: smtp.login(user=self.smtp_user, password=self.smtp_password) # # Email versenden # self.statusdict = smtp.sendmail( from_str, (self.recipients.get_list() + self.cc_recipients.get_list() + self.bcc_recipients.get_list()), msg.as_string(), ) smtp.close() # Rueckmeldung return True