def __mimeData(filename, msg): fp = open(filename, 'rb') data = MIMENonMultipart('application', 'pdf', name=os.path.basename(filename), charset='us-ascii') data.set_payload(base64.encodestring(fp.read())) data.add_header('Content-Transfer-Encoding', 'base64') fp.close() msg.attach(data) return data
def sendNonMultipartMail(context, sender, receiver, cc=[], bcc=[], subject="", text="", charset="utf-8"): """ """ mail = MIMENonMultipart("text", "plain") mail['From'] = sender mail['To'] = receiver mail['Cc'] = ", ".join(cc) mail['Bcc'] = ", ".join(bcc) mail['Subject'] = subject text = text.encode("utf-8") mail.set_payload(text) context.MailHost.send(mail.as_string())
def send_email(email_to, email_from, email_subject, email_body): msg = MIMENonMultipart('text', 'plain') msg['Content-Transfer-Encoding'] = '8bit' msg.set_payload(email_body, 'utf-8') msg['From'] = email_from msg['Subject'] = Header(email_subject, 'utf-8') server = smtplib.SMTP(config.smtp_host, config.smtp_port) server.ehlo() server.starttls() server.ehlo() server.login(email_from, config.email_password) for addr in email_to: msg['To'] = addr body = msg.as_string() server.sendmail(email_from, addr, body, '8bitmime') server.quit()
def generate(self, fp): msg = MIMEMultipart(_subtype='related') msg['Subject'] = 'archived' msg.epilogue = '' # Guarantees the message ends in a newline for res in self.resource_list: if '/' in res.ctype_actual: maintype, subtype = res.ctype_actual.split('/',1) else: maintype, subtype = res.ctype_actual, '' part = MIMENonMultipart(maintype, subtype) part.set_payload(res.data) part['content-location'] = res.uri Encoders.encode_base64(part) msg.attach(part) # generate the MIME message Generator(fp, False).flatten(msg)
def addAttachment(self, path): filename = os.path.split(path)[-1] ext = os.path.splitext(filename)[-1] subtype = mime_types.get(ext, "octet-stream") msgAttachment = MIMENonMultipart("application", subtype, name=filename) fp = open(path, 'rb') msgAttachment.set_payload(fp.read()) fp.close() Encoders.encode_base64(msgAttachment) id = "attach_%s" % self.next self.next += 1 msgAttachment.add_header('Content-ID', id) self.root.attach(msgAttachment)
def getAttachments(self): attachments = [] # attach files for data, content_type, filename, disposition in \ self.context.getAttachments(): maintype, subtype = content_type.split('/') msg = MIMENonMultipart(maintype, subtype) msg.set_payload(data) if filename: msg['Content-Id'] = '<%s@z3ext>' % filename msg['Content-Disposition'] = '%s; filename="%s"' % ( disposition, filename) Encoders.encode_base64(msg) attachments.append(msg) return attachments
def sendEmail(mail, subj): fromaddr = "*****@*****.**" toaddr = ["*****@*****.**", "*****@*****.**"] #toaddr = ["*****@*****.**"] msg = MIMENonMultipart('text', 'plain') msg['Content-Transfer-Encoding'] = '8bit' msg.set_payload(mail.encode('utf8'), 'utf-8') msg['From'] = fromaddr msg['To'] = toaddr[0] msg['Subject'] = subj server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.ehlo() server.login(settings.email, settings.emailpass) body = msg.as_string() server.sendmail(fromaddr, toaddr[0], body, '8bitmime') msg['To'] = toaddr[1] body = msg.as_string() server.sendmail(fromaddr, toaddr[1], body, '8bitmime') server.quit()
def addAttachment(self, attachment, filename, mimetype=None): "Do³¹cza do wiadomoœci wskazany plik." #Odgadnij g³ówny i dodatkowy typ MIME na podstawie nazwy pliku. if not mimetype: mimetype = mimetypes.guess_type(filename)[0] if not mimetype: raise Exception, "Nie uda³o siê okreœliæ typu MIME dla", filename if '/' in mimetype: major, minor = mimetype.split('/') else: major = mimetype minor = None #Wiadomoœæ by³a konstruowana z za³o¿eniem, i¿ bêdzie zawieraæ #tylko i wy³¹cznie tekst. Poniewa¿ wiem, ¿e bêdzie zawieraæ #co najmniej jeden za³¹cznik, musimy zmieniæ j¹ na wiadomoœæ #wieloczêœciow¹ i wkleiæ tekst jako pierwsz¹ czêœæ. if not self.hasAttachments: body = self.msg.get_payload() newMsg = MIMEMultipart() newMsg.attach(MIMEText(body, 'plain', self.enc)) #Skopiuj stare nag³ówki do nowego obiektu. for header, value in self.msg.items(): newMsg[header] = value self.msg = newMsg self.hasAttachments = True subMessage = MIMENonMultipart(major, minor, name=filename) subMessage.set_payload(attachment) #Zakoduj teksty jako quoted printable natomiast wszystkie #inne typy jako base64. if major == 'text': encoder = Encoders.encode_quopri else: encoder = Encoders.encode_base64 encoder(subMessage) #Powi¹¿ fragment MIME z g³ówn¹ wiadomoœci¹. self.msg.attach(subMessage)
def to_mail(self): message = MIMEMultipart('alternative') try: author = self.author except AttributeError: try: author = self.feed.author except AttributeError: try: author = self.feed.title except AttributeError: author = self.feed.name message['From'] = '%s <rsspull@localhost>' % author message['To'] = Feed.recipient message['Date'] = self.timestamp.strftime( '%a, %d %b %Y %H:%M:%S +0000') # XXX: msgid? message['Subject'] = ws.rsspull.util.header(self.title) message['X-RSS-Id'] = self.feed.name message['Content-Location'] = self.resolved_link body = self.body body = ws.rsspull.util.expandNumEntities(body) body = ws.rsspull.util.fixQuotes(body) body = ws.rsspull.util.html2text(body).strip() body += '\n\n' + 'Link: [ ' + self.resolved_link + ' ]\n' text_part = MIMEText(body.encode('utf-8'), 'plain', 'utf-8') html_part = MIMENonMultipart('text', 'html', charset='utf-8') html_body = self.body if sys.version_info < (3, ): html_body = html_body.encode('utf-8') html_part.set_payload(html_body) message.attach(text_part) message.attach(html_part) return message
def odf2mht(self, odtfile): tmpfile = saveodtfile(odtfile) self.REQUEST.RESPONSE.setHeader('Content-Type', 'message/rfc822') msg = MIMEMultipart('related', type="text/html") msg.preamble = 'This is a multi-part message in MIME format.' msg.epilogue = '' result = odf2xhtml(tmpfile).encode('us-ascii', 'xmlcharrefreplace') htmlpart = MIMEText(result, 'html', 'us-ascii') htmlpart['Content-Location'] = 'index.html' msg.attach(htmlpart) z = zipfile.ZipFile(tmpfile) for file in z.namelist(): if file[0:9] == 'Pictures/': suffix = file[file.rfind(".") + 1:] main, sub = suffices.get(suffix, ('application', 'octet-stream')) img = MIMENonMultipart(main, sub) img.set_payload(z.read(file)) img['Content-Location'] = "" + file Encoders.encode_base64(img) msg.attach(img) z.close() unlink(tmpfile) return msg.as_string()
def sendEmail(mail, subj): fromaddr = "*****@*****.**" toaddr = [ "*****@*****.**", "*****@*****.**" ] #toaddr = ["*****@*****.**"] msg = MIMENonMultipart('text', 'plain') msg['Content-Transfer-Encoding'] = '8bit' msg.set_payload(mail.encode('utf8'), 'utf-8') msg['From'] = fromaddr msg['To'] = toaddr[0] msg['Subject'] = subj server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.ehlo() server.login(settings.email, settings.emailpass) body = msg.as_string() server.sendmail(fromaddr, toaddr[0], body, '8bitmime') msg['To'] = toaddr[1] body = msg.as_string() server.sendmail(fromaddr, toaddr[1], body, '8bitmime') server.quit()
author_name=detail[2] author_email=detail[3] coauthor_name=detail[4] coauthor_email=detail[5] ref_no=detail[6] msg=MIMEMultipart() msg['From']=formataddr((str(Header('Paper Presentation Team, BITS Pilani', 'utf-8')), '*****@*****.**')) msg['To']=author_email msg['Subject']='Paper Presentation, APOGEE 2016' msg.attach(MIMEText(body %(author_name.encode('ascii'),title.encode('ascii'),category.encode('ascii')), 'html')) #attach PDF fp=open((ref_no+'.pdf').decode('ascii'),'rb') attach = MIMENonMultipart('application', 'pdf') payload = base64.b64encode(fp.read()).decode('ascii') attach.set_payload(payload) attach['Content-Transfer-Encoding'] = 'base64' fp.close() attach.add_header('Content-Disposition', 'attachment', filename = ref_no+'_report.pdf') msg.attach(attach) toadr=author_email try: server.sendmail(fromadr,toadr,msg.as_string()) time.sleep(30) print "Mail sent to "+toadr except smtplib.SMTPRecipientsRefused: print "Mail not sent to "+toadr except smtplib.SMTPServerDisconnected: print "Server disconneted"
def add_a_post(groupId, siteId, replyToId, topic, message, tags, email, uploadedFiles, context, request): result = {'error': False, 'message': "Message posted.", 'id': ''} site_root = context.site_root() assert site_root userInfo = createObject('groupserver.LoggedInUser', context) siteObj = getattr(site_root.Content, siteId) groupObj = getattr(siteObj.groups, groupId) messages = getattr(groupObj, 'messages') assert messages listManager = messages.get_xwfMailingListManager() assert listManager groupList = getattr(listManager, groupObj.getId()) assert groupList #audit = WebPostAuditor(groupObj) #audit.info(POST, topic) # Step 1, check if the user can post userPostingInfo = getMultiAdapter((groupObj, userInfo), IGSPostingUser) if not userPostingInfo.canPost: raise 'Forbidden', userPostingInfo.status # --=mpj17-- Bless WebKit. It adds a file, even when no file has # been specified; if the files are empty, do not add the files. uploadedFiles = [f for f in uploadedFiles if f] # Step 2, Create the message # Step 2.1 Body message = message.encode('utf-8') if uploadedFiles: msg = MIMEMultipart() msgBody = MIMEText(message, 'plain', 'utf-8') # As God intended. msg.attach(msgBody) else: msg = MIMEText(message, 'plain', 'utf-8') # Step 2.2 Headers # msg['To'] set below # TODO: Add the user's name. The Header class will be needed # to ensure it is escaped properly. msg['From'] = unicode(Addressee(userInfo, email)).encode('ascii', 'ignore') msg['Subject'] = topic # --=mpj17=-- This does not need encoding. tagsList = tagProcess(tags) tagsString = ', '.join(tagsList) if tagsString: msg['Keywords'] = tagsString if replyToId: msg['In-Reply-To'] = replyToId # msg['Reply-To'] set by the list # Step 2.3 Attachments for f in uploadedFiles: # --=mpj17=-- zope.formlib has already read the data, so we # seek to the beginning to read it all again :) f.seek(0) data = f.read() if data: t = f.headers.getheader('Content-Type', 'application/octet-stream') mimePart = MIMENonMultipart(*t.split('/')) mimePart.set_payload(data) mimePart['Content-Disposition'] = 'attachment' filename = removePathsFromFilenames(f.filename) mimePart.set_param('filename', filename, 'Content-Disposition') encode_base64(mimePart) # Solves a lot of problems. msg.attach(mimePart) # Step 3, check the moderation. # --=mpj17=-- This changes *how* we send the message to the # mailing list. No, really. via_mailserver = False moderatedlist = groupList.get_moderatedUserObjects(ids_only=True) moderated = groupList.getValueFor('moderated') # --=rrw=--if we are moderated _and_ we have a moderatedlist, only # users in the moderated list are moderated if moderated and moderatedlist and (userInfo.id in moderatedlist): log.warn('User "%s" posted from web while moderated' % userInfo.id) via_mailserver = True # --=rrw=-- otherwise if we are moderated, everyone is moderated elif moderated and not (moderatedlist): log.warn('User "%s" posted from web while moderated' % userInfo.id) via_mailserver = True errorM = 'The post was not added to the topic '\ '<code class="topic">%s</code> because a post with the same '\ 'body already exists in the topic.' % topic # Step 4, send the message. for list_id in messages.getProperty('xwf_mailing_list_ids', []): curr_list = listManager.get_list(list_id) msg['To'] = curr_list.getValueFor('mailto') if via_mailserver: # If the message is being moderated, we have to emulate # a post via email so it can go through the moderation # subsystem. mailto = curr_list.getValueFor('mailto') try: send_email(email, mailto, msg.as_string()) except BadRequest as e: result['error'] = True result['message'] = errorM log.error(e.encode('ascii', 'ignore')) break result['error'] = True result['message'] = 'Your message has been sent to the '\ 'moderators for approval.' break else: # Send the message directly to the mailing list because # it is not moderated try: request = {'Mail': msg.as_string()} r = groupList.manage_listboxer(request) result['message'] = \ '<a href="/r/topic/%s#post-%s">Message '\ 'posted.</a>' % (r, r) except BadRequest as e: result['error'] = True result['message'] = errorM log.error(e) break except DuplicateMessageError as e: result['error'] = True result['message'] = errorM break if (not r): # --=mpj17=-- This could be lies. result['error'] = True result['message'] = errorM break return result
def add_a_post(groupId, siteId, replyToId, topic, message, tags, email, uploadedFiles, context, request): result = { 'error': False, 'message': "Message posted.", 'id': ''} site_root = context.site_root() assert site_root userInfo = createObject('groupserver.LoggedInUser', context) siteObj = getattr(site_root.Content, siteId) groupObj = getattr(siteObj.groups, groupId) messages = getattr(groupObj, 'messages') assert messages listManager = messages.get_xwfMailingListManager() assert listManager groupList = getattr(listManager, groupObj.getId()) assert groupList #audit = WebPostAuditor(groupObj) #audit.info(POST, topic) # Step 1, check if the user can post userPostingInfo = getMultiAdapter((groupObj, userInfo), IGSPostingUser) if not userPostingInfo.canPost: raise 'Forbidden', userPostingInfo.status # --=mpj17-- Bless WebKit. It adds a file, even when no file has # been specified; if the files are empty, do not add the files. uploadedFiles = [f for f in uploadedFiles if f] # Step 2, Create the message # Step 2.1 Body message = message.encode('utf-8') if uploadedFiles: msg = MIMEMultipart() msgBody = MIMEText(message, 'plain', 'utf-8') # As God intended. msg.attach(msgBody) else: msg = MIMEText(message, 'plain', 'utf-8') # Step 2.2 Headers # msg['To'] set below # TODO: Add the user's name. The Header class will be needed # to ensure it is escaped properly. msg['From'] = unicode(Addressee(userInfo, email)).encode('ascii', 'ignore') msg['Subject'] = topic # --=mpj17=-- This does not need encoding. tagsList = tagProcess(tags) tagsString = ', '.join(tagsList) if tagsString: msg['Keywords'] = tagsString if replyToId: msg['In-Reply-To'] = replyToId # msg['Reply-To'] set by the list # Step 2.3 Attachments for f in uploadedFiles: # --=mpj17=-- zope.formlib has already read the data, so we # seek to the beginning to read it all again :) f.seek(0) data = f.read() if data: t = f.headers.getheader('Content-Type', 'application/octet-stream') mimePart = MIMENonMultipart(*t.split('/')) mimePart.set_payload(data) mimePart['Content-Disposition'] = 'attachment' filename = removePathsFromFilenames(f.filename) mimePart.set_param('filename', filename, 'Content-Disposition') encode_base64(mimePart) # Solves a lot of problems. msg.attach(mimePart) # Step 3, check the moderation. # --=mpj17=-- This changes *how* we send the message to the # mailing list. No, really. via_mailserver = False moderatedlist = groupList.get_moderatedUserObjects(ids_only=True) moderated = groupList.getValueFor('moderated') # --=rrw=--if we are moderated _and_ we have a moderatedlist, only # users in the moderated list are moderated if moderated and moderatedlist and (userInfo.id in moderatedlist): log.warn('User "%s" posted from web while moderated' % userInfo.id) via_mailserver = True # --=rrw=-- otherwise if we are moderated, everyone is moderated elif moderated and not(moderatedlist): log.warn('User "%s" posted from web while moderated' % userInfo.id) via_mailserver = True errorM = 'The post was not added to the topic '\ '<code class="topic">%s</code> because a post with the same '\ 'body already exists in the topic.' % topic # Step 4, send the message. for list_id in messages.getProperty('xwf_mailing_list_ids', []): curr_list = listManager.get_list(list_id) msg['To'] = curr_list.getValueFor('mailto') if via_mailserver: # If the message is being moderated, we have to emulate # a post via email so it can go through the moderation # subsystem. mailto = curr_list.getValueFor('mailto') try: send_email(email, mailto, msg.as_string()) except BadRequest as e: result['error'] = True result['message'] = errorM log.error(e.encode('ascii', 'ignore')) break result['error'] = True result['message'] = 'Your message has been sent to the '\ 'moderators for approval.' break else: # Send the message directly to the mailing list because # it is not moderated try: request = {'Mail': msg.as_string()} r = groupList.manage_listboxer(request) result['message'] = \ '<a href="/r/topic/%s#post-%s">Message '\ 'posted.</a>' % (r, r) except BadRequest as e: result['error'] = True result['message'] = errorM log.error(e) break except DuplicateMessageError as e: result['error'] = True result['message'] = errorM break if (not r): # --=mpj17=-- This could be lies. result['error'] = True result['message'] = errorM break return result