def construct_email(self, metadata, key='reminder_message'): message = MIMEText(metadata[key]) message['To'] = email.utils.formataddr( (metadata['fullname'], metadata[self.prefix + 'id'])) # not sure if this line is very relevant atm. #message['CC'] = ", ".join(map(lambda p: email.utils.formataddr(p), metadata.get(self.prefix + 'recipients', ())) message_id = metadata.get(self.prefix + 'message_id', None) if message_id: message['In-Reply-To'] = message_id message.set_payload( metadata.get(key, "Error message from %s" % (self.my_email_address))) message['From'] = email.utils.formataddr( (self.my_email_name, self.my_email_address[0])) prefix = 'REMINDER: ' if metadata.get('is_reminder', False) else 'Re: ' message['Subject'] = prefix + metadata[self.prefix + 'subject'] print message # evt_date = metadata[''] # message['Date'] = evt_date # TODO add Date header. return message
def _getAttachment(self, attachmentFilePath): contentType, encoding = mimetypes.guess_type(attachmentFilePath) if contentType is None or encoding is not None: contentType = 'application/octet-stream' mainType, subType = contentType.split('/', 1) file = open(attachmentFilePath, 'rb') if mainType == 'text': attachment = MIMEText(file.read()) elif mainType == 'message': attachment = email.message_from_file(file) elif mainType == 'image': attachment = MIMEImage(file.read(),_subType=subType) elif mainType == 'audio': attachment = MIMEAudio(file.read(),_subType=subType) else: attachment = MIMEBase(mainType, subType) attachment.set_payload(file.read()) encode_base64(attachment) file.close() attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachmentFilePath)) return attachment
def getAttachments(msg, attachmentDirPath): for filename in os.listdir(attachmentDirPath): path = os.path.join(attachmentDirPath, filename) if not os.path.isfile(path): continue contentType, encoding = mimetypes.guess_type(path) if contentType is None or encoding is not None: contentType = 'application/octet-stream' mainType, subType = contentType.split('/', 1) fp = open(path, 'rb') if mainType == 'text': attachment = MIMEText(fp.read()) elif mainType == 'image': attachment = MIMEImage(fp.read(), _subType=subType) elif mainType == 'audio': attachment = MIMEAudio(fp.read(), _subType=subType) else: attachment = MIMEBase(mainType, subType) attachment.set_payload(fp.read()) encode_base64(attachment) fp.close() attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(path)) msg.attach(attachment)
def _FILE(file_name): """Guess the content type based on the file's extension. Encoding will be ignored, altough we should check for simple things like gzip'd or compressed files.""" base_name = str(Header(os.path.basename(file_name))) file_type, encoding = mimetypes.guess_type(file_name) if file_type is None or encoding is not None: # No guess could be made, or the file is encoded (compressed), so # use a generic bag-of-bits type. file_type = "application.octet-stream" maintype, subtype = file_type.split("/", 1) if maintype == "text": fp = open(file_name) # Note : we should handle calculating the charset msg = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == "image": fp = open(file_name, "rb") msg = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == "audio": fp = open(file_name, "rb") msg = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = open(file_name, "rb") msg = MIMEBase(maintype, subtype) # , name=base_name) msg.set_payload(fp.read()) fp.close() # Encode the payload using Base64 Encoders.encode_base64(msg) # Set the filename parameter msg.add_header("Content-Disposition", "attachment", filename=base_name) return msg
def file2msg (file): ## TODO: check if file exists ctype, encoding = mimetypes.guess_type(file) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/') print "==> Adding file [%s] using [%s]" % (file, ctype) if maintype == "text": fp = open(file) msg = MIMEText(fp.read(), _subtype = subtype) fp.close() elif maintype == "image": fp = open(file, 'rb') msg = MIMEImage(fp.read(), _subtype = subtype) fp.close() elif maintype == "audio": fp = open(file, 'rb') msg = MIMEAudio(fp.read(), _subtype = subtype) fp.close() else: fp = open(file, 'rb') msg = MIMEBase(maintype, subtype) msg.set_payload(fp.read()) fp.close() Encoders.encode_base64(msg) return msg
def get_mail_text(self, fields, request, **kwargs): """ Get header and body of e-amil as text (string) This will create both parts of the e-mail: text and the XML file """ headerinfo, additional_headers, body = self.get_header_body_tuple(fields, request, **kwargs) body_xml = self.get_mail_text_in_xml(fields, request, **kwargs) self.safe_xml_in_filesystem(body_xml) mime_text = MIMEText(body, _subtype=self.body_type or 'html', _charset=self._site_encoding()) attachments = self.get_attachments(fields, request) outer = MIMEMultipart() outer.attach(mime_text) # write header for key, value in headerinfo.items(): outer[key] = value # write additional header for a in additional_headers: key, value = a.split(':', 1) outer.add_header(key, value.strip()) for attachment in attachments: filename = attachment[0] ctype = attachment[1] encoding = attachment[2] content = attachment[3] if ctype is None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': msg = MIMEText(content, _subtype=subtype) elif maintype == 'image': msg = MIMEImage(content, _subtype=subtype) elif maintype == 'audio': msg = MIMEAudio(content, _subtype=subtype) else: msg = MIMEBase(maintype, subtype) msg.set_payload(content) # Encode the payload using Base64 Encoders.encode_base64(msg) # Set the filename parameter msg.add_header('Content-Disposition', 'attachment', filename=filename) outer.attach(msg) ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) p = MIMEBase(maintype, subtype) p.set_payload(body_xml) p.add_header('content-disposition', 'attachment', filename='form.xml') Encoders.encode_base64(p) outer.attach(p) return outer.as_string()
def send_email_copy(message): """ Sends an email copy of a message to all relevant targets. """ receivers = [ receiver for receiver in message.receivers if receiver.player.user.email ] subject = message.header body = message.message if not (receivers): return msg = MIMEMultipart('alternative') msg['From'] = "Winter's Oasis <*****@*****.**>" msg['Subject'] = subject msg['Date'] = formatdate(localtime=True) # HTML email part. html_part = MIMEText('text', 'html') html_source = Template(HTML_TEMPLATE) value_map = { 'from' : ', '.join([ sender.name for sender in message.senders ]), 'message' : escape(unicode(body)).replace('\n', '<br />'), 'recipients' : ', '.join([ receiver.name for receiver in message.receivers ]) } html_part.set_payload(html_source.substitute(value_map)) value_map['message'] = unicode(body) text_source = Template(TEXT_TEMPLATE) body = text_source.substitute(value_map) text_part = MIMEText(unicode(body), 'plain', 'utf-8') msg.attach(text_part) msg.attach(html_part) for receiver in receivers: msg['To'] = receiver.db.email sendmail(SMTP_HOST, MAIL_FROM, receiver.player.user.email, msg.as_string())
def append(self, content=None, content_file_path=None, content_encondig=None, filename=None, content_type=None, **kwargs): if content_file_path: if content_type == None: (content_type, content_encondig) = mimetypes.guess_type(content_file_path, strict=False) if content == None: with open(content_file_path, 'r') as fh: content = fh.read() content_class = content.__class__.__name__ if content_class in self.mapper: message = self.mapper[content_class](self, content, **kwargs) else: if not content_type: content_type = guess_mime_type(content, 'binary/octet-stream') (maintype, subtype) = content_type.split('/') if maintype == 'text': message = MIMEText(content, _subtype=subtype) else: message = MIMEBase(maintype, subtype) message.set_payload(content) #Dont base64 encode rfc822 message, they will not be parsed if not content_type == 'message/rfc822': Encoders.encode_base64(message) if content_encondig != None: message['Content-Encoding'] = content_encondig if filename != None: message.add_header('Content-Disposition', 'attachment', filename=filename) if message != None: self.message.attach(message) else: raise OSLibError("Empty part added to user_data")
def main(): msg = MIMEMultipart() msg['Subject'] = subject msg['To'] = recipient msg['From'] = sender part = MIMEText('text', "plain") part.set_payload(message) msg.attach(part) session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT) session.ehlo() session.starttls() session.ehlo session.login(sender, password) qwertyuiop = msg.as_string() session.sendmail(sender, recipient, qwertyuiop) session.quit() print "Email has been sent."
def send_email(percentage): import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEImage import MIMEImage from email.MIMEText import MIMEText # Prepare actual message msg = MIMEMultipart() msg['From'] = "*****@*****.**" # change to your mail msg['To'] = "*****@*****.**" # change to your mail msg['Subject'] = "RPi Camera Alarm!" imgcv = Image("image.jpg") imgcv.save("imagesend.jpg", quality=50) # reducing quality of the image for smaller size img1 = MIMEImage(open("imagesend.jpg","rb").read(), _subtype="jpg") img1.add_header('Content-Disposition', 'attachment; filename="image.jpg"') msg.attach(img1) part = MIMEText('text', "plain") part.set_payload(("Raspberry Pi camera alarm activated with level {:f}").format(percentage)) msg.attach(part) try: server = smtplib.SMTP("mail.htnet.hr", 25) #change to your SMTP provider server.ehlo() server.starttls() server.sendmail(msg['From'], msg['To'], msg.as_string()) server.quit() print 'Successfully sent the mail' except smtplib.SMTPException as e: print(e)
def mail(to, subject, html,attach): msg = MIMEMultipart() gmail_pwd = getpass.getpass(stream=sys.stderr) msg['From'] = gmail_user msg['To'] = to msg['Subject'] = subject part = MIMEText(html, 'html') msg.attach(part) if attach!="": msg.attach(MIMEText(text)) part = MIMEBase('application', 'octet-stream') part.set_payload(open(attach, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attach)) msg.attach(part) try: mailServer = smtplib.SMTP("smtp.gmail.com", 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(gmail_user, gmail_pwd) mailServer.sendmail(gmail_user, to, msg.as_string()) # Should be mailServer.quit(), but that crashes... mailServer.close() print 'Mail sent!' except : print 'Failure!'
def getAttachment(attachmentFilePath): contentType, encoding = mimetypes.guess_type(attachmentFilePath) if contentType is None or encoding is not None: contentType = 'application/octet-stream' mainType, subType = contentType.split('/', 1) file = open(attachmentFilePath, 'rb') if mainType == 'text': attachment = MIMEText(file.read()) elif mainType == 'message': attachment = email.message_from_file(file) elif mainType == 'image': attachment = MIMEImage(file.read(), _subType=subType) elif mainType == 'audio': attachment = MIMEAudio(file.read(), _subType=subType) else: attachment = MIMEBase(mainType, subType) attachment.set_payload(file.read()) encode_base64(attachment) file.close() ## 设置附件头 attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachmentFilePath)) return attachment
def send_email(percentage): import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEImage import MIMEImage from email.MIMEText import MIMEText # Prepare actual message msg = MIMEMultipart() msg['From'] = "*****@*****.**" # change to your mail msg['To'] = "*****@*****.**" # change to your mail msg['Subject'] = "RPi Camera Alarm!" imgcv = Image("image.jpg") imgcv.save("imagesend.jpg", quality=50) # reducing quality of the image for smaller size img1 = MIMEImage(open("imagesend.jpg", "rb").read(), _subtype="jpg") img1.add_header('Content-Disposition', 'attachment; filename="image.jpg"') msg.attach(img1) part = MIMEText('text', "plain") part.set_payload(("Raspberry Pi camera alarm activated with level {:f}" ).format(percentage)) msg.attach(part) try: server = smtplib.SMTP("mail.htnet.hr", 25) #change to your SMTP provider server.ehlo() server.starttls() server.sendmail(msg['From'], msg['To'], msg.as_string()) server.quit() print 'Successfully sent the mail' except smtplib.SMTPException as e: print(e)
def construct_email_message(sender, to_list, cc_list, subject, mtext, attachment_list): """ # """ outer = MIMEMultipart() outer['From'] = sender outer['To'] = ', '.join(to_list) outer['Cc'] = ', '.join(cc_list) outer['Subject'] = subject outer.preample = 'You will not see this in a MIME-aware mail reader.\n' outer.epilogue = '' # plain text body msg = MIMEText(mtext + '\n\n') msg.add_header('Content-Disposition', 'inline') outer.attach(msg) # file attachments # outer.add_header('Content-Transfer-Encoding', 'base64') for att in attachment_list: if not os.path.isfile(att): continue ctype, encoding = mimetypes.guess_type(att) maintype, subtype = ctype.split('/', 1) fp = open(att, 'rb') msg = MIMEBase(maintype, subtype) # msg = MIMEBase('application', 'octet-stream') msg.set_payload(fp.read()) Encoders.encode_base64(msg) basename = att.split('/')[-1] msg.add_header('Content-Disposition', 'attachment', filename=basename) outer.attach(msg) return outer
def attach(mesg, response): """ attach a handler response to our return mail""" global log (type, out) = response maintype, subtype = type.split('/', 1) log.debug("%s part type" % maintype) if maintype == 'text': data = MIMEText(out, _subtype=subtype) log.debug("Result is:\n%s" % out) elif maintype == 'image': data = MIMEImage(out, _subtype=subtype) elif maintype == 'audio': data = MIMEAudio(out, _subtype=subtype) else: # Generic mime encoding data = MIMEBase(maintype, subtype) data.set_payload(out) Encoders.encode_base64(data) mesg.attach(data)
def main(): msg = MIMEMultipart() msg['Subject'] = sys.argv[2] msg['To'] = recipient msg['From'] = sender part = MIMEText('text', "plain") part.set_payload(message) msg.attach(part) session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT) session.ehlo() session.starttls() session.ehlo session.login(sender, password) # Now send or store the message qwertyuiop = msg.as_string() session.sendmail(sender, recipient, qwertyuiop) session.quit() os.system('notify-send "Email sent"')
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 main(): msg = MIMEMultipart() msg['Subject'] = subject msg['To'] = recipient msg['From'] = sender part = MIMEText('text', "plain") part.set_payload(message) msg.attach(part) session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT) session.ehlo() fp = open(sys.argv[4], 'rb') msgq = MIMEBase('audio', 'audio') msgq.set_payload(fp.read()) fp.close() # Encode the payload using Base64 encoders.encode_base64(msgq) # Set the filename parameter msgq.add_header('Content-Disposition', 'attachment', filename=nicefilename) msg.attach(msgq) # Now send or store the message qwertyuiop = msg.as_string() session.sendmail(sender, recipient, qwertyuiop) session.quit()
def send_mail(script_code,log_file): jsonstr=read_file("email.cfg") email_cfg=json.JSONDecoder().decode(jsonstr) import smtplib import mimetypes from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.MIMEAudio import MIMEAudio from email.MIMEImage import MIMEImage from email.Encoders import encode_base64 from email import Encoders from email.utils import COMMASPACE, formatdate #sg_root = MIMEMultipart('related') msg_root = MIMEMultipart() msg_root['From'] = os.environ["MAIL_FROM"] smtp_server = os.environ["SMTP_SERVER"] smtp_username = os.environ["SMTP_USERNAME"] smtp_password = os.environ["SMTP_PASSWORD"] mail_from = os.environ["MAIL_FROM"] mail_to_str = email_cfg["recipions"][script_code] mail_to = mail_to_str.split(";") msg_root['To'] = mail_to msg_root['Subject'] = " Batch job [%s] is done" % script_code html_mail_body=read_file(log_file) msg = MIMEMultipart() msg['Subject'] = " Batch job [%s] is done" % script_code msg.attach(MIMEText(html_mail_body,'plain','utf-8')) msg_root.attach(msg) #msg_root.attach(MIMEText(html_mail_body,'plain','utf-8')) log("script_code is %s" % script_code) if str(script_code) == '011': wbName = 'company_scores_' + str(get_last_date()) + '.xls' filePath = '/app/gmbatch/scripts/miles/statScript/xls/' + wbName fd = file(filePath,"rb") mimetype,mimeencoding = mimetypes.guess_type(filePath) if mimeencoding or (mimetype is None): mimetype = "application/octet-stream" maintype,subtype = mimetype.split("/") if maintype == "text": retval = MIMEText(fd.read(), _subtype = subtype) else: retval = MIMEBase(maintype,subtype) retval.set_payload(fd.read()) Encoders.encode_base64(retval) retval.add_header("Content-Disposition","attachment",filename = wbName) fd.close() msg.attach(retval) mailServer = smtplib.SMTP(smtp_server, 25) mailServer.ehlo() mailServer.ehlo() mailServer.login(smtp_username, smtp_password) mailServer.sendmail(mail_from, mail_to, msg.as_string()) mailServer.close() log("email send to %s" % mail_to)
def make_attach(path): path = os.path.abspath(path) contentType, encoding = mimetypes.guess_type(path) if contentType is None or encoding is not None: contentType = "application/octet-stream" main_type, sub_type = contentType.split("/", 1) f = open(path, "rb") bytes = f.read() f.close() if main_type == "text": attachment = MIMEText(bytes) elif main_type == "message": attachment = email.message_from_string(bytes) elif main_type == "image": attachment = MIMEImage(bytes, sub_type) attachment.add_header("Content-ID", "".join(("<", os.path.basename(path), ">"))) elif main_type == "audio": print sub_type attachment = MIMEAudio(bytes, sub_type) else: attachment = MIMEBase(main_type, sub_type) attachment.set_payload(bytes) encode_base64(attachment) attachment.add_header("Content-Disposition", "attachment", filename=os.path.basename(path)) return attachment
def file2msg(file): ## TODO: check if file exists ctype, encoding = mimetypes.guess_type(file) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/') print "==> Adding file [%s] using [%s]" % (file, ctype) if maintype == "text": fp = open(file) msg = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == "image": fp = open(file, 'rb') msg = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == "audio": fp = open(file, 'rb') msg = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = open(file, 'rb') msg = MIMEBase(maintype, subtype) msg.set_payload(fp.read()) fp.close() Encoders.encode_base64(msg) return msg
def getAttachments(msg,attachmentDirPath): for filename in os.listdir(attachmentDirPath): path = os.path.join(attachmentDirPath, filename) if not os.path.isfile(path): continue contentType, encoding = mimetypes.guess_type(path) if contentType is None or encoding is not None: contentType = 'application/octet-stream' mainType, subType = contentType.split('/', 1) fp = open(path, 'rb') if mainType == 'text': attachment = MIMEText(fp.read()) elif mainType == 'image': attachment = MIMEImage(fp.read(),_subType=subType) elif mainType == 'audio': attachment = MIMEAudio(fp.read(),_subType=subType) else: attachment = MIMEBase(mainType, subType) attachment.set_payload(fp.read()) encode_base64(attachment) fp.close() attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(path)) msg.attach(attachment)
def get_content_data(self, data, filename, charset=None): "Vrátí data jako instanci třídy odvozené od MIMEBase." # Guess the content type based on the file's extension. Encoding # will be ignored, although we should check for simple things like # gzip'd or compressed files. ctype, encoding = mimetypes.guess_type(filename) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compressed), so # use a generic bag-of-bits type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': # Note: we should handle calculating the charset if not charset: charset = self.charset content = MIMEText(data, _subtype=subtype, _charset=charset) elif maintype == 'image': content = MIMEImage(data, _subtype=subtype) elif maintype == 'audio': content = MIMEAudio(data, _subtype=subtype) else: content = MIMEBase(maintype, subtype) content.set_payload(data) email.Encoders.encode_base64(content) return content
def sendMail(mail_subject, mail_to, mail_message): """ Send a email message. @params: mail_subject - Required : subject of mail mail_to - Required : dest of mail mail_message - Required : message of mail """ msg = MIMEMultipart() msg['Subject'] = mail_subject msg['To'] = mail_to msg['From'] = SMTP_SENDER part = MIMEText('text', "plain") part.set_payload(mail_message) msg.attach(part) # sets parameters to send email session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT) session.ehlo() session.starttls() session.ehlo # login using sender parameters session.login(SMTP_SENDER, SMTP_PASSWORD) qwertyuiop = msg.as_string() # sends email session.sendmail(SMTP_SENDER, mail_to, qwertyuiop) # close session session.quit()
def main(): print("I am running the py script!") msg = MIMEMultipart() msg['Subject'] = sys.argv[2] msg['To'] = recipient msg['From'] = sender part = MIMEText('text', "plain") part.set_payload(message) msg.attach(part) msg.attach(MIMEText(BODY_HTML, 'html')) session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT) session.ehlo() session.starttls() session.ehlo session.login(sender, password) # Now send or store the message qwertyuiop = msg.as_string() session.sendmail(sender, recipient, qwertyuiop) session.quit()
def get_mail_text(self, fields, request, **kwargs): """Get header and body of e-mail as text (string) """ (headerinfo, additional_headers, body) = self.get_header_body_tuple(fields, request, **kwargs) if not isinstance(body, unicode): body = unicode(body, self._site_encoding()) portal = getToolByName(self, "portal_url").getPortalObject() email_charset = portal.getProperty("email_charset", "utf-8") # always use text/plain for encrypted bodies subtype = getattr(self, "gpg_keyid", False) and "plain" or self.body_type or "html" mime_text = MIMEText(body.encode(email_charset, "replace"), _subtype=subtype, _charset=email_charset) attachments = self.get_attachments(fields, request) if attachments: outer = MIMEMultipart() outer.attach(mime_text) else: outer = mime_text # write header for key, value in headerinfo.items(): outer[key] = value # write additional header for a in additional_headers: key, value = a.split(":", 1) outer.add_header(key, value.strip()) for attachment in attachments: filename = attachment[0] ctype = attachment[1] # encoding = attachment[2] content = attachment[3] if ctype is None: ctype = "application/octet-stream" maintype, subtype = ctype.split("/", 1) if maintype == "text": msg = MIMEText(content, _subtype=subtype) elif maintype == "image": msg = MIMEImage(content, _subtype=subtype) elif maintype == "audio": msg = MIMEAudio(content, _subtype=subtype) else: msg = MIMEBase(maintype, subtype) msg.set_payload(content) # Encode the payload using Base64 Encoders.encode_base64(msg) # Set the filename parameter msg.add_header("Content-Disposition", "attachment", filename=filename) outer.attach(msg) return outer.as_string()
def get_mail_text(self, fields, request, **kwargs): """Get header and body of e-mail as text (string) """ (headerinfo, additional_headers, body) = self.get_header_body_tuple(fields, request, **kwargs) if not isinstance(body, unicode): body = unicode(body, self._site_encoding()) portal = getToolByName(self, 'portal_url').getPortalObject() email_charset = portal.getProperty('email_charset', 'utf-8') mime_text = MIMEText(body.encode(email_charset , 'replace'), _subtype=self.body_type or 'html', _charset=email_charset) attachments = self.get_attachments(fields, request) if attachments: outer = MIMEMultipart() outer.attach(mime_text) else: outer = mime_text # write header for key, value in headerinfo.items(): outer[key] = value # write additional header for a in additional_headers: key, value = a.split(':', 1) outer.add_header(key, value.strip()) for attachment in attachments: filename = attachment[0] ctype = attachment[1] encoding = attachment[2] content = attachment[3] if ctype is None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': msg = MIMEText(content, _subtype=subtype) elif maintype == 'image': msg = MIMEImage(content, _subtype=subtype) elif maintype == 'audio': msg = MIMEAudio(content, _subtype=subtype) else: msg = MIMEBase(maintype, subtype) msg.set_payload(content) # Encode the payload using Base64 Encoders.encode_base64(msg) # Set the filename parameter msg.add_header('Content-Disposition', 'attachment', filename=filename) outer.attach(msg) return outer.as_string()
def __createMultipartMail(self): """ Private method to create a multipart mail message. @return string containing the mail message """ try: import sipconfig sip_version_str = sipconfig.Configuration().sip_version_str except ImportError: sip_version_str = "sip version not available" mpPreamble = ( "This is a MIME-encoded message with attachments. " "If you see this message, your mail client is not " "capable of displaying the attachments." ) msgtext = "%s\r\n----\r\n%s----\r\n%s----\r\n%s" % ( unicode(self.message.toPlainText()), Utilities.generateVersionInfo("\r\n"), Utilities.generatePluginsVersionInfo("\r\n"), Utilities.generateDistroInfo("\r\n"), ) # first part of multipart mail explains format msg = MIMEMultipart() msg["From"] = unicode(Preferences.getUser("Email")) msg["To"] = self.__toAddress msg["Subject"] = "[eric4] %s" % unicode(self.subject.text()) msg.preamble = mpPreamble msg.epilogue = "" # second part is intended to be read att = MIMEText(msgtext, _charset=unicode(Preferences.getSystem("StringEncoding"))) msg.attach(att) # next parts contain the attachments for index in range(self.attachments.topLevelItemCount()): itm = self.attachments.topLevelItem(index) maintype, subtype = str(itm.text(1)).split("/", 1) fname = unicode(itm.text(0)) name = os.path.basename(fname) if maintype == "text": att = MIMEText(open(fname, "rb").read(), _subtype=subtype) elif maintype == "image": att = MIMEImage(open(fname, "rb").read(), _subtype=subtype) elif maintype == "audio": att = MIMEAudio(open(fname, "rb").read(), _subtype=subtype) else: att = MIMEBase(maintype, subtype) att.set_payload(open(fname, "rb").read()) Encoders.encode_base64(att) att.add_header("Content-Disposition", "attachment", filename=name) msg.attach(att) return msg.as_string()
def genpart(data, contenttype): maintype, subtype = contenttype.split('/') if maintype == 'text': retval = MIMEText(data, _subtype=subtype) else: retval = MIMEBase(maintype, subtype) retval.set_payload(data) Encoders.encode_base64(retval) return retval
def alternative(data, contenttype): maintype, subtype = contenttype.split('/') if maintype == 'text': retval = MIMEText(data, _subtype=subtype) else: retval = MIMEBase(maintype, subtype) retval.set_payload(data) Encoders.encode_base64(retval) return retval
def create(subj, to, body): outer = MIMEMultipart() subj = subj.encode("iso-2022-jp") outer["Subject"] = Header(subj, "iso-2022-jp") outer["From"] = mine outer["To"] = to mainpart = MIMEText("", _charset="iso-2022-jp") mainpart.set_payload(body.encode("iso-2022-jp")) outer.attach(mainpart) return outer
def sendAPI(sender, to, subject, body, attachment=None): try: service = authAPI() message = MIMEMultipart() message['to'] = to message['from'] = sender message['subject'] = subject msg = MIMEText(body, 'html') message.attach(msg) if attachment != None: mime = MimeTypes() content_type, encoding = mime.guess_type(attachment) if content_type is None or encoding is not None: content_type = 'application/octet-stream' main_type, sub_type = content_type.split('/', 1) if main_type == 'text': fp = open(attachment, 'rb') msg = MIMEText(fp.read(), _subtype=sub_type) fp.close() elif main_type == 'image': fp = open(attachment, 'rb') msg = MIMEImage(fp.read(), _subtype=sub_type) fp.close() elif main_type == 'audio': fp = open(attachment, 'rb') msg = MIMEAudio(fp.read(), _subtype=sub_type) fp.close() else: fp = open(attachment, 'rb') msg = MIMEBase(main_type, sub_type) msg.set_payload(fp.read()) fp.close() filename = os.path.basename(attachment) msg.add_header('Content-Disposition', 'attachment', filename=filename) message.attach(msg) message = { 'raw': base64.urlsafe_b64encode(message.as_string()), 'payload': { 'mimeType': 'text/html' } } message = (service.users().messages().send(userId=sender, body=message).execute()) return True, '' except Exception, error: return False, error
def mailHtmlAsAttachement(self, fileName, subject): print 'mailHtmlAsAttachement with subject "%s"' % subject import mimetypes from email import encoders from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase # getting address & smtp servers fromA, toA, smtpServ = self.getMailData() # building email mail = MIMEMultipart() mail['From'] = fromA mail['To'] = toA mail['Subject'] = subject #mail.preamble = 'Battery result in attachement \n' machineName = socket.gethostname() from email.MIMEText import MIMEText text = "Battery result on %s in attachement ...\n" % machineName msg = MIMEText(text, 'html','iso-8859-1') msg['From'] = fromA msg['To'] = toA msg['Subject'] = subject mail.attach(msg) ctype, encoding = mimetypes.guess_type(fileName) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compressed), so # use a generic bag-of-bits type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) try: file = open(fileName,'r') print "file %s correctly opened for mailing" % fileName msg = MIMEBase(maintype, subtype) msg.set_payload(file.read()) file.close() print "file %s correctly closed after mailing" % fileName except smtplib.SMTPException: text="file %s not found"%fileName # Encode the payload using Base64 encoders.encode_base64(msg) (head, tail) = os.path.split(fileName) newFileName = "%s-%s" %(machineName,tail) msg.add_header('Content-Disposition', 'attachment', filename=newFileName) mail.attach(msg) try: print "opening smtp" import smtplib smtp = smtplib.SMTP(smtpServ) #smtp.set_debuglevel(True) smtp.sendmail(fromA, toA, mail.as_string()) smtp.close() print "closing smtp" except smtplib.SMTPException, e: print "mailHtmlAsAttachement: error during smtp sendmail !!!" print "smtplib.SMTPException returned: %s"%e
def _paramsToMime(params, filenames, files): """ """ mimeMsg = MIMEMultipart("form-data") for name, value in params.iteritems(): mimeItem = MIMEText(value) mimeItem.add_header("Content-Disposition", "form-data", name=name) # TODO: Handle this better...? for hdr in [ 'Content-Type', 'MIME-Version', 'Content-Transfer-Encoding' ]: del mimeItem[hdr] mimeMsg.attach(mimeItem) if filenames or files: filenames = filenames or [] files = files or [] for idx, item in enumerate(filenames + files): # TODO: This is messy, tidy it... if isinstance(item, str): # We assume it's a file path... filename = item contentType = mimetypes.guess_type(filename)[0] payload = open(filename, "rb").read() else: # We assume it's an `email.Message.Message` instance... # TODO: Make more use of the pre-encoded information? filename = item.get_filename() contentType = item.get_content_type() payload = item.get_payload(decode=True) if not contentType: contentType = "application/octet-stream" mimeItem = MIMEBase(*contentType.split("/")) mimeItem.add_header("Content-Disposition", "form-data", name="file%s" % idx, filename=filename) # TODO: Encode the payload? mimeItem.set_payload(payload) # TODO: Handle this better...? for hdr in ['MIME-Version', 'Content-Transfer-Encoding']: del mimeItem[hdr] mimeMsg.attach(mimeItem) del mimeMsg['MIME-Version'] return mimeMsg
def main(args): # variables attach_file = False # check input file if args.attachment is not None: attach_file = True if not file_exists(args.attachment): sys.stderr.write("[main] Error: input file doesn't exist (%s)\n" % args.infile) return 1 recipient = args.to subject = args.subject message = args.message msg = MIMEMultipart() msg['Subject'] = subject msg['To'] = recipient msg['From'] = sender part = MIMEText('text', "plain") part.set_payload(message) msg.attach(part) session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT) session.ehlo() # session.starttls() session.ehlo session.login(sender, password) if attach_file: fp = open(args.attachment, 'rb') msgq = MIMEBase('audio', 'audio') msgq.set_payload(fp.read()) fp.close() # Encode the payload using Base64 encoders.encode_base64(msgq) # Set the filename parameter filename = args.attachment msgq.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(msgq) # Now send or store the message qwertyuiop = msg.as_string() session.sendmail(sender, recipient, qwertyuiop) session.quit() os.system('notify-send "Email sent"')
def pir(): time.sleep(2) current_state = GPIO.input(13) if current_state == 0: print "No intruders",current_state GPIO.output(3, 0) time.sleep(0.5) if current_state == 1: GPIO.output(3, 1) time.sleep(0.5) print "Intruder detected",current_state subprocess.call("fswebcam -d /dev/video0 + /home/pi/project -r 1024x768 -S 3 + pic.jpg" ,shell=True) print("pic captured") time.sleep(0.5) filePath = "pic.jpg" smtp = smtplib.SMTP('smtp.gmail.com:587') smtp.starttls() smtp.login('*****@*****.**', 'pimcp3008') ctype, encoding = mimetypes.guess_type(filePath) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': fp = open(filePath) part = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == 'image': fp = open(filePath, 'rb') part = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == 'audio': fp = open(filePath, 'rb') part = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = open(filePath, 'rb') part = MIMEBase(maintype, subtype) part.set_payload(fp.read()) fp.close() Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % filePath) msg.attach(part) try: smtp.sendmail(From, To, msg.as_string()) except: print "Mail not sent" else: print "Mail sent" smtp.close() else: print "Connection failed"
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 sendMail(mfrom,mto,subject,content,files=[],add_server_name=False,smtp_server="localhost"): '''Send and email and also deals with attachments''' assert type(mto)==list assert type(files)==list outer = MIMEMultipart() outer['From'] = mfrom outer['To'] = COMMASPACE.join(mto) outer['Date'] = formatdate(localtime=True) outer['Subject'] = subject if add_server_name: outer['Subject'] = subject+" @ "+socket.gethostname() outer.attach(MIMEText(content,_charset='utf-8')) for name in files: if os.path.isfile(name): ctype, encoding = mimetypes.guess_type(name,False) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compressed), so # use a generic bag-of-bits type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': fp = open(name) # Note: we should handle calculating the charset msg = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == 'image': fp = open(name, 'rb') msg = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == 'audio': fp = open(name, 'rb') msg = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = open(name, 'rb') msg = MIMEBase(maintype, subtype) msg.set_payload(fp.read()) fp.close() #Encode the payload using Base64 Encoders.encode_base64(msg) # Set the filename parameter msg.add_header('Content-Disposition', 'attachment', name=name) outer.attach(msg) smtp = smtplib.SMTP(smtp_server) smtp.sendmail(mfrom,mto,outer.as_string()) smtp.close()
def _paramsToMime(params, filenames, files): """ """ mimeMsg = MIMEMultipart("form-data") for name, value in params.iteritems(): mimeItem = MIMEText(value) mimeItem.add_header("Content-Disposition", "form-data", name=name) # TODO: Handle this better...? for hdr in ['Content-Type','MIME-Version','Content-Transfer-Encoding']: del mimeItem[hdr] mimeMsg.attach(mimeItem) if filenames or files: filenames = filenames or [] files = files or [] for idx, item in enumerate(filenames + files): # TODO: This is messy, tidy it... if isinstance(item, str): # We assume it's a file path... filename = item contentType = mimetypes.guess_type(filename)[0] payload = open(filename, "rb").read() else: # We assume it's an `email.Message.Message` instance... # TODO: Make more use of the pre-encoded information? filename = item.get_filename() contentType = item.get_content_type() payload = item.get_payload(decode=True) if not contentType: contentType = "application/octet-stream" mimeItem = MIMEBase(*contentType.split("/")) mimeItem.add_header("Content-Disposition", "form-data", name="file%s" % idx, filename=filename) # TODO: Encode the payload? mimeItem.set_payload(payload) # TODO: Handle this better...? for hdr in ['MIME-Version','Content-Transfer-Encoding']: del mimeItem[hdr] mimeMsg.attach(mimeItem) del mimeMsg['MIME-Version'] return mimeMsg
def attachment( self, filename, fd): mimetype, mimeencoding = mimetypes.guess_type(filename) if mimeencoding or (mimetype is None): mimetype = 'application/octet-stream' maintype, subtype = mimetype.split('/') if maintype == 'text': retval = MIMEText(fd.read(), _subtype=subtype, _charset='latin-1') else: retval = MIMEBase(maintype, subtype) retval.set_payload(fd.read()) Encoders.encode_base64(retval) retval.add_header('Content-Disposition', 'attachment', filename = filename) fd.close() return retval
def httprequest(self, postdata): if not self.anubisURL.startswith("http://"): raise "Invalid URL, only http:// URLs are allowed: url='%s'" % ( self.anubisURL) if not postdata: raise "Invalid/No POST data supplied: postdata='%s'" % (postdata) headers = {} headers["Content-Type"] = "multipart/form-data" message = MIMEMultipart(_subtype="form-data") ### notification element part = MIMEText(None) part.set_payload(postdata["notification"], "us-ascii") part.add_header("Content-Disposition", "form-data", name="notification") message.attach(part) ### email element part = MIMEText(None) part.set_payload(postdata["email"], "us-ascii") part.add_header("Content-Disposition", "form-data", name="email") message.attach(part) ### type element part = MIMEText(None) part.set_payload(postdata["analysisType"], "us-ascii") part.add_header("Content-Disposition", "form-data", name="analysisType") message.attach(part) ### file data element part = MIMEBase('application', "octet-stream") part.set_payload(postdata['executable']['content']) ### Add content-disposition header. dispHeaders = postdata["executable"].get("headers", {}) part.add_header("Content-Disposition", "form-data", name="executable", filename=postdata["executable"]["filename"]) for dhName, dhValue in dispHeaders: part.add_header(dhName, dhValue) message.attach(part) message.epilogue = "" headerBlock, body = message.as_string().split("\n\n", 1) for hName, hValue in message.items(): headers[hName] = hValue ### Make the HTTP request and get the response. ### Precondition: 'url', 'method', 'headers', 'body' are all setup properly. scheme, netloc, path, parameters, query, fragment = urlparse.urlparse( self.anubisURL) if parameters or query or fragment: raise "Unexpected URL: parameters=%r, query=%r, fragment=%r" % ( parameters, query, fragment) try: conn = httplib.HTTPConnection(netloc) conn.request("POST", path, body, headers) response = conn.getresponse() except socket.error, e: response = ConnRes(404, e)
def attachment(filename): fd = open(filename, 'rb') mimetype, mimeencoding = mimetypes.guess_type(filename) if mimeencoding or (mimetype is None): mimetype = 'application/octet-stream' maintype, subtype = mimetype.split('/') if maintype == 'text': retval = MIMEText(fd.read(), _subtype=subtype) else: retval = MIMEBase(maintype, subtype) retval.set_payload(fd.read()) Encoders.encode_base64(retval) retval.add_header('Content-Disposition', 'attachment', filename = filename) fd.close() return retval
def mandar_mail(fileName, filePath, To): From = '*****@*****.**' msg = MIMEMultipart() msg['From'] = From msg['To'] = To msg['Date'] = formatdate(localtime=True) msg['Subject'] = fileName msg.attach(MIMEText(' ')) smtp = smtplib.SMTP('smtp.gmail.com:587') smtp.starttls() smtp.login('*****@*****.**', 'Emprender1') # try: # smtp = smtplib.SMTP('smtp.gmail.com:587') smtp.starttls() # smtp.login('*****@*****.**', 'kazo001') except: i = 1 # else: i = 0 ctype, encoding = mimetypes.guess_type(filePath) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compressed), # so use a generic bag-of-bits type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': fp = open(filePath) # Note: we should handle calculating the charset part = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == 'image': fp = open(filePath, 'rb') part = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == 'audio': fp = open(filePath, 'rb') part = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = open(filePath, 'rb') part = MIMEBase(maintype, subtype) part.set_payload(fp.read()) fp.close() # Encode the payload using Base64 Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % fileName) msg.attach(part) smtp.sendmail(From, To, msg.as_string()) smtp.close()
def ecommerce_sendmail(self, cr, uid, mail_to, subject, body, attachment=None, context={}): try: mail_from = '*****@*****.**' s = smtplib.SMTP('smtp.gmail.com', 587) s.set_debuglevel(1) s.ehlo() s.starttls() s.ehlo() s.login('*****@*****.**', '123456') outer = MIMEMultipart() outer['Subject'] = 'Invoice:' outer['To'] = mail_to outer['From'] = "noreply" outer.preamble = 'You will not see this in a MIME-aware mail reader.\n' msg = MIMEText(body or '', _charset='utf-8') if (attachment == None): msg['Subject'] = Header(subject.decode('utf8'), 'utf-8') msg['From'] = "noreply" s.sendmail(mail_from, mail_to, msg.as_string()) else: msg.set_payload(attachment) Encoders.encode_base64(msg) msg.add_header('Content-Disposition', 'attachment', filename='invoice.pdf') outer.attach(msg) outer.attach(MIMEText(body)) composed = outer.as_string() s.sendmail(mail_from, mail_to, composed) s.close() except Exception, e: logging.getLogger().error(str(e))
def write_mime_multipart(content, compress=False, deftype='text/plain', delimiter=':'): """Description: :param content: A list of tuples of name-content pairs. This is used instead of a dict to ensure that scripts run in order :type list of tuples: :param compress: Use gzip to compress the scripts, defaults to no compression :type bool: :param deftype: The type that should be assumed if nothing else can be figured out :type str: :param delimiter: mime delimiter :type str: :return: Final mime multipart :rtype: str: """ wrapper = MIMEMultipart() for name, con in content: definite_type = guess_mime_type(con, deftype) maintype, subtype = definite_type.split('/', 1) if maintype == 'text': mime_con = MIMEText(con, _subtype=subtype) else: mime_con = MIMEBase(maintype, subtype) mime_con.set_payload(con) # Encode the payload using Base64 Encoders.encode_base64(mime_con) mime_con.add_header('Content-Disposition', 'attachment', filename=name) wrapper.attach(mime_con) rcontent = wrapper.as_string() if compress: buf = StringIO.StringIO() gz = gzip.GzipFile(mode='wb', fileobj=buf) try: gz.write(rcontent) finally: gz.close() rcontent = buf.getvalue() return rcontent
def addAttachments(self, mainmsg, bodytext, attaches): # format a multi-part message with attachments msg = MIMEText(bodytext) # add main text/plain part mainmsg.attach(msg) for filename in attaches: # absolute or relative paths if not os.path.isfile(filename): # skip dirs, etc. continue # guess content type from file extension, ignore encoding contype, encoding = mimetypes.guess_type(filename) if contype is None or encoding is not None: # no guess, compressed? contype = 'application/octet-stream' # use generic default self.trace('Adding ' + contype) # build sub-Message of apropriate kind maintype, subtype = contype.split('/', 1) if maintype == 'text': data = open(filename, 'r') msg = MIMEText(data.read(), _subtype=subtype) data.close() elif maintype == 'image': data = open(filename, 'rb') msg = MIMEImage(data.read(), _subtype=subtype) data.close() elif maintype == 'audio': data = open(filename, 'rb') msg = MIMEAudio(data.read(), _subtype=subtype) data.close() else: data = open(filename, 'rb') msg = MIMEBase(maintype, subtype) msg.set_payload(data.read()) data.close() # make generic type email.Encoders.encode_base64(msg) # encode using Base64 # set filename and attach to container basename = os.path.basename(filename) msg.add_header('Content-Disposition', 'attachment', filename=basename) mainmsg.attach(msg) # text outside mime structure, seen by non-MIME mail readers mainmsg.preamble = 'A multi-part MIME format message.\n' mainmsg.epilogue = '' # make sure message ends with a newline
def getAttachment(attachmentFilePath): name = 'getAttachment' printpoint = "" from email.MIMEText import MIMEText from email.MIMEBase import MIMEBase from email.MIMEImage import MIMEImage from email import Encoders import mimetypes, base64 contentType, encoding = mimetypes.guess_type(attachmentFilePath) if contentType is None or encoding is not None: contentType = 'application/octet-stream' mainType, subType = contentType.split('/', 1) file = open(attachmentFilePath, 'rb') if mainType == 'text': attachment = MIMEText(file.read()) elif mainType == 'message': attachment = email.message_from_file(file) elif mainType == 'image': attachment = MIMEImage(file.read(), _subType=subType) elif mainType == 'audio': attachment = MIMEAudio(file.read(), _subType=subType) else: attachment = MIMEBase(mainType, subType) attachment.set_payload(file.read()) encoders.encode_base64(attachment) file.close() attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachmentFilePath)) text = "attachmentFilePath" + space2 + str(attachmentFilePath) + newline + \ "contentType" + space2 + str(contentType) + newline + \ "encoding" + space2 + str(encoding) + newline + \ "mainType" + space2 + str(mainType) + newline + \ "subType" + space2 + str(subType) + newline #"attachment" + space2 + str(attachment) printlog(title='getAttachment', printpoint=printpoint, text=text, level=0, option="") return attachment
def addAttachments(self, mainmsg, bodytext, attaches): # format a multipart message with attachments msg = MIMEText(bodytext) # add main text/plain part mainmsg.attach(msg) for filename in attaches: # absolute or relative paths if not os.path.isfile(filename): # skip dirs, etc. continue # guess content type from file extension, ignore encoding contype, encoding = mimetypes.guess_type(filename) if contype is None or encoding is not None: # no guess, compressed? contype = 'application/octet-stream' # use generic default print>>sys.stderr,'Adding ' + contype # build sub-Message of appropriate kind maintype, subtype = contype.split('/', 1) if maintype == 'text': data = open(filename, 'r') msg = MIMEText(data.read( ), _subtype=subtype) data.close( ) elif maintype == 'image': data = open(filename, 'rb') msg = MIMEImage(data.read( ), _subtype=subtype) data.close( ) elif maintype == 'audio': data = open(filename, 'rb') msg = MIMEAudio(data.read( ), _subtype=subtype) data.close( ) else: data = open(filename, 'rb') msg = MIMEBase(maintype, subtype) msg.set_payload(data.read( )) data.close( ) # make generic type email.Encoders.encode_base64(msg) # encode using base64 # set filename and attach to container basename = os.path.basename(filename) msg.add_header('Content-Disposition', 'attachment', filename=basename) mainmsg.attach(msg) # text outside mime structure, seen by non-MIME mail readers mainmsg.preamble = 'A multi-part MIME format message.\n' mainmsg.epilogue = '' # make sure message ends with a newline
def write_mime_multipart(content, compress=False, deftype='text/plain', delimiter=':'): """Description: :param content: A list of tuples of name-content pairs. This is used instead of a dict to ensure that scripts run in order :type list of tuples: :param compress: Use gzip to compress the scripts, defaults to no compression :type bool: :param deftype: The type that should be assumed if nothing else can be figured out :type str: :param delimiter: mime delimiter :type str: :return: Final mime multipart :rtype: str: """ wrapper = MIMEMultipart() for name,con in content: definite_type = guess_mime_type(con, deftype) maintype, subtype = definite_type.split('/', 1) if maintype == 'text': mime_con = MIMEText(con, _subtype=subtype) else: mime_con = MIMEBase(maintype, subtype) mime_con.set_payload(con) # Encode the payload using Base64 Encoders.encode_base64(mime_con) mime_con.add_header('Content-Disposition', 'attachment', filename=name) wrapper.attach(mime_con) rcontent = wrapper.as_string() if compress: buf = StringIO.StringIO() gz = gzip.GzipFile(mode='wb', fileobj=buf) try: gz.write(rcontent) finally: gz.close() rcontent = buf.getvalue() return rcontent
def send_mail(self, target, subject, body, *file_names): """ send a mail with files to the target @param target: send the mail to the target @param subject: mail's subject @param file_names= list of files to send """ msg = MIMEMultipart() msg['From'] = self.mail msg['To'] = target msg['Subject'] = subject body_part = MIMEText(body, 'plain') msg.attach(body_part) for file_name in file_names: f = open(file_name, 'rb') ctype, encoding = mimetypes.guess_type(file_name) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) # in case of a text file if maintype == 'text': part = MIMEText(f.read(), _subtype=subtype) # in case of an image file elif maintype == 'image': part = MIMEImage(f.read(), _subtype=subtype) # in case of an audio file elif maintype == 'audio': part = MIMEAudio(f.read(), _subtype=subtype) # any other file else: part = MIMEBase(maintype, subtype) part.set_payload(f.read()) encoders.encode_base64(part) part.add_header( 'Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file_name)) msg.attach(part) f.close() # ssl server doesn't support or need tls, # so don't call server_ssl.starttls() self.server_ssl.sendmail(self.mail, target, msg.as_string()) self.server_ssl.quit()
def makemail(subjstr, toaddr, body, filename): """サブジェクトと本文を渡してMessageオブジェクトを作る filenameにファイル名やパスを渡し、画像ファイルを添付する """ outer = MIMEMultipart() # Messageオブジェクトを作る subjstr = subjstr.encode("iso-2022-jp") # 件名をエンコード subj = Header(subjstr, "iso-2022-jp") outer["Subject"] = subj # ヘッダに設定 outer["From"] = fromaddr # 送信元をヘッダに outer["To"] = toaddr # 送信先をヘッダに mainpart = MIMEText("", _charset = "iso-2022-jp") mainpart.set_payload(body.encode("iso-2022-jp")) outer.attach(mainpart) # Messageオブジェクトに追加 img = MIMEImage(open(filename).read()) img.add_header('Content-Disposition', # ファイル名を設定 'attachment', filename = 'takigawa.jpg') outer.attach(img) # Messageオブジェクトに追加 return outer
def msgDef(text="", html="", img="", subject="", azienda="ND"): if not azienda: azienda = "OneBasic" msgg = MIMEMultipart() msgg['Subject'] = azienda\ + " "\ + str(datetime.datetime.now().strftime('%d_%m_%Y_%H_%M')) msgg['From'] = "*****@*****.**" msgg['To'] = "*****@*****.**" msgg.attach(MIMEText(text)) part = MIMEText('text/plain') fp = open(LOG_FILENAME, 'rb') part.set_payload(fp.read()) fp.close() # Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment', filename="pg2.log") msgg.attach(part) _send(fromaddr="*****@*****.**", total_addrs="*****@*****.**", msg=msgg)
def attachFile(path, multipart, assumedCharset=_7BIT_CHARSET): # Guess the content type based on the file's extension. Encoding # will be ignored, although we should check for simple things like # gzip'd or compressed files. ctype, encoding = mimetypes.guess_type(path) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compressed), so # use a generic bag-of-bits type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': fp = open(path, 'rt') txt = fp.read() txt, charset = safelyEncode(txt, assumedCharset) # If the file was not pure ascii, but we encoded it, # report the encoding we're *going* to use, not the one # the file was in originally.' if charset != _7BIT_CHARSET: charset = _PREFERRED_NONASCII_CHARSET msg = MIMEText(txt, subtype, charset) fp.close() elif maintype == 'image': fp = open(path, 'rb') msg = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == 'audio': fp = open(path, 'rb') msg = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = open(path, 'rb') msg = MIMEBase(maintype, subtype) txt = fp.read() msg.set_payload(fp.read()) fp.close() # Set the filename parameter msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(path)) multipart.attach(msg)
def sendMail(filename): msg = MIMEMultipart() msg['Subject'] = subject msg['To'] = recipient msg['From'] = sender part = MIMEText('text', "plain") part.set_payload(message) msg.attach(part) msg.attach(load_attachment(filename)) session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT) session.ehlo() session.starttls() session.ehlo session.login(sender, password) session.sendmail(sender, recipient, msg.as_string()) session.quit()
def getAttachment(attachmentFilePath,size): if isinstance(size,str): size=int(size) if not os.path.exists(attachmentFilePath): warn('Attachment path is invalid: '+attachmentFilePath) contentType, encoding = mimetypes.guess_type(attachmentFilePath) print "ContentType:",contentType,"\n encoding:",encoding,"\n path:",attachmentFilePath if contentType is None or encoding is not None: print "Doing the octet stream encoding." contentType = 'application/octet-stream' mainType, subType = contentType.split('/', 1) fp = open(attachmentFilePath, 'rb') if mainType == 'text': attachment = MIMEText(fp.read()) elif mainType == 'message': attachment = email.message_from_file(fp) # these produce an empty attachment" elif mainType == 'image': # this corrupts the image that is ultimately sent out # attachment = MIMEImage(fp.read(),_subType=subType) if size: fp.close() newAttachmentFilePath = resize_image(attachmentFilePath,max_dimension = size) fp = open(newAttachmentFilePath, 'rb') # elif mainType == 'audio': # attachment = MIMEAudio(fp.read(),_subType=subType) attachment = MIMEBase(mainType, subType) else: attachment = MIMEBase(mainType, subType) attachment.set_payload(fp.read()) encode_base64(attachment) fp.close() attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachmentFilePath)) return attachment
def send_email_copy(message): """ Sends an email copy of a message to all relevant targets. """ receivers = [ receiver for receiver in message.receivers if receiver.player.user.email ] subject = message.header body = message.message if not (receivers): return msg = MIMEMultipart('alternative') msg['From'] = "Winter's Oasis <*****@*****.**>" msg['Subject'] = subject msg['Date'] = formatdate(localtime=True) # HTML email part. html_part = MIMEText('text', 'html') html_source = Template(HTML_TEMPLATE) value_map = { 'from': ', '.join([sender.name for sender in message.senders]), 'message': escape(unicode(body)).replace('\n', '<br />'), 'recipients': ', '.join([receiver.name for receiver in message.receivers]) } html_part.set_payload(html_source.substitute(value_map)) value_map['message'] = unicode(body) text_source = Template(TEXT_TEMPLATE) body = text_source.substitute(value_map) text_part = MIMEText(unicode(body), 'plain', 'utf-8') msg.attach(text_part) msg.attach(html_part) for receiver in receivers: msg['To'] = receiver.db.email sendmail(SMTP_HOST, MAIL_FROM, receiver.player.user.email, msg.as_string())
def patch_to_attachment(self, patch, index): # patches don't come with an encoding. If the patch is valid utf-8, # we'll attach it as MIMEText; otherwise, it gets attached as a binary # file. This will suit the vast majority of cases, since utf8 is by # far the most common encoding. if type(patch[1]) != types.UnicodeType: try: unicode = patch[1].decode('utf8') except UnicodeDecodeError: unicode = None else: unicode = patch[1] if unicode: a = MIMEText(unicode.encode(ENCODING), _charset=ENCODING) else: # MIMEApplication is not present in Python-2.4 :( a = MIMENonMultipart('application', 'octet-stream') a.set_payload(patch[1]) a.add_header('Content-Disposition', "attachment", filename="source patch " + str(index) ) return a