我们从Python开源项目中,提取了以下46个代码示例,用于说明如何使用email.mime.image.MIMEImage()。
def image(xml_element): template_path = xml_element.attrib["template"] template_dir = os.path.abspath(os.path.dirname(template_path)) if "src" in xml_element.attrib: path = xml_element.attrib["src"].strip() tmp = os.path.join(template_dir, path) if (not os.path.exists(path)): if os.path.exists(tmp): path = tmp else: msg = "file '{}' not found.[not found at '{}' as well]" raise Exception(msg.format(path, tmp)) fp = open(path, 'rb') msgImage = MIMEImage(fp.read()) if "id" in xml_element.attrib.keys(): msgImage.add_header('Content-ID', '<{}>'.format(xml_element.attrib["id"])) fp.close() return msgImage else: raise Exception("src for image not specified")
def test_add_header(self): eq = self.assertEqual unless = self.failUnless self._au.add_header('Content-Disposition', 'attachment', filename='audiotest.au') eq(self._au['content-disposition'], 'attachment; filename="audiotest.au"') eq(self._au.get_params(header='content-disposition'), [('attachment', ''), ('filename', 'audiotest.au')]) eq(self._au.get_param('filename', header='content-disposition'), 'audiotest.au') missing = [] eq(self._au.get_param('attachment', header='content-disposition'), '') unless(self._au.get_param('foo', failobj=missing, header='content-disposition') is missing) # Try some missing stuff unless(self._au.get_param('foobar', missing) is missing) unless(self._au.get_param('attachment', missing, header='foobar') is missing) # Test the basic MIMEImage class
def test__all__(self): module = __import__('email') # Can't use sorted() here due to Python 2.3 compatibility all = module.__all__[:] all.sort() self.assertEqual(all, [ # Old names 'Charset', 'Encoders', 'Errors', 'Generator', 'Header', 'Iterators', 'MIMEAudio', 'MIMEBase', 'MIMEImage', 'MIMEMessage', 'MIMEMultipart', 'MIMENonMultipart', 'MIMEText', 'Message', 'Parser', 'Utils', 'base64MIME', # new names 'base64mime', 'charset', 'encoders', 'errors', 'generator', 'header', 'iterators', 'message', 'message_from_file', 'message_from_string', 'mime', 'parser', 'quopriMIME', 'quoprimime', 'utils', ])
def test_add_header(self): eq = self.assertEqual self._au.add_header('Content-Disposition', 'attachment', filename='audiotest.au') eq(self._au['content-disposition'], 'attachment; filename="audiotest.au"') eq(self._au.get_params(header='content-disposition'), [('attachment', ''), ('filename', 'audiotest.au')]) eq(self._au.get_param('filename', header='content-disposition'), 'audiotest.au') missing = [] eq(self._au.get_param('attachment', header='content-disposition'), '') self.assertIs(self._au.get_param('foo', failobj=missing, header='content-disposition'), missing) # Try some missing stuff self.assertIs(self._au.get_param('foobar', missing), missing) self.assertIs(self._au.get_param('attachment', missing, header='foobar'), missing) # Test the basic MIMEImage class
def test_add_header(self): eq = self.assertEqual unless = self.assertTrue self._au.add_header('Content-Disposition', 'attachment', filename='audiotest.au') eq(self._au['content-disposition'], 'attachment; filename="audiotest.au"') eq(self._au.get_params(header='content-disposition'), [('attachment', ''), ('filename', 'audiotest.au')]) eq(self._au.get_param('filename', header='content-disposition'), 'audiotest.au') missing = [] eq(self._au.get_param('attachment', header='content-disposition'), '') unless(self._au.get_param('foo', failobj=missing, header='content-disposition') is missing) # Try some missing stuff unless(self._au.get_param('foobar', missing) is missing) unless(self._au.get_param('attachment', missing, header='foobar') is missing) # Test the basic MIMEImage class
def embed_image(message, dir_path, file_name): """Attach an image to an email. Parameters ---------- message : |Message| The email message to which the image will be attached. dir_path : |str| The path for the directory containing the image file. file_name : |str| The name of the image file. """ message.mixed_subtype = 'related' file_path = os.path.join(dir_path, file_name) with open(file_path, 'rb') as image_file: image = MIMEImage(image_file.read()) image.add_header('Content-ID', '<{}>'.format(file_name)) message.attach(image) return message
def get_attachments(self): attachments = super().get_attachments() filename = ( finders.find('images/email_logo.png') or finders.find('images/email_logo.svg') ) if filename: if filename.endswith('.png'): imagetype = 'png' else: imagetype = 'svg+xml' with open(filename, 'rb') as f: logo = MIMEImage(f.read(), imagetype) logo.add_header('Content-ID', '<{}>'.format('logo')) return attachments + [logo] return attachments
def send_photos(self, recipients=[], subject='', message='', image_paths=[]): try: multipart = MIMEMultipart() multipart['Subject'] = subject multipart['From'] = self.config.smtp_username multipart['To'] = COMMASPACE.join(recipients) text = MIMEText(message, 'plain') multipart.attach(text) for image_path in image_paths: image_data = open(image_path, 'rb').read() multipart.attach(MIMEImage(image_data, name=os.path.basename(image_path))) self.send_email(recipients, multipart.as_string()) except Exception as ex: self.logger.error('EmailSender (send_photos):\n{0}'.format(ex)) pass
def send_attached_image(image_file, message, toaddr, fromaddr=''): img_data = open(image_file, 'rb').read() msg = MIMEMultipart() text = MIMEText(message) msg.attach(text) image = MIMEImage(img_data, name=os.path.basename(image_file)) msg.attach(image) server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo() server.starttls() server.ehlo() server.login(USERNAME, PASSWORD) server.sendmail(fromaddr, toaddr, msg.as_string()) server.quit()
def test_attached_images(self): image_filename = SAMPLE_IMAGE_FILENAME image_path = sample_image_path(image_filename) image_data = sample_image_content(image_filename) self.message.attach_file(image_path) # option 1: attach as a file image = MIMEImage(image_data) # option 2: construct the MIMEImage and attach it directly self.message.attach(image) self.message.send() image_data_b64 = b64encode(image_data).decode('ascii') data = self.get_api_call_json() self.assertEqual(data['attachments'][0], { 'filename': image_filename, # the named one 'content': image_data_b64, 'type': "image/png", }) self.assertEqual(data['attachments'][1], { 'filename': '', # the unnamed one 'content': image_data_b64, 'type': "image/png", })
def test_attached_images(self): image_filename = SAMPLE_IMAGE_FILENAME image_path = sample_image_path(image_filename) image_data = sample_image_content(image_filename) self.message.attach_file(image_path) # option 1: attach as a file image = MIMEImage(image_data) # option 2: construct the MIMEImage and attach it directly self.message.attach(image) self.message.send() files = self.get_api_call_files() self.assertEqual(files, { 'files[%s]' % image_filename: (image_filename, image_data, "image/png"), # the named one 'files[]': ('', image_data, "image/png"), # the unnamed one })
def test_attached_images(self): image_filename = SAMPLE_IMAGE_FILENAME image_path = sample_image_path(image_filename) image_data = sample_image_content(image_filename) self.message.attach_file(image_path) # option 1: attach as a file image = MIMEImage(image_data) # option 2: construct the MIMEImage and attach it directly self.message.attach(image) self.message.send() files = self.get_api_call_files() attachments = [value for (field, value) in files if field == 'attachment'] self.assertEqual(len(attachments), 2) self.assertEqual(attachments[0], (image_filename, image_data, 'image/png')) self.assertEqual(attachments[1], (None, image_data, 'image/png')) # name unknown -- not attached as file # Make sure the image attachments are not treated as inline: inlines = [value for (field, value) in files if field == 'inline'] self.assertEqual(len(inlines), 0)
def test_attached_images(self): image_filename = SAMPLE_IMAGE_FILENAME image_path = sample_image_path(image_filename) image_data = sample_image_content(image_filename) self.message.attach_file(image_path) # option 1: attach as a file image = MIMEImage(image_data) # option 2: construct the MIMEImage and attach it directly self.message.attach(image) self.message.send() params = self.get_send_params() attachments = params['attachments'] self.assertEqual(len(attachments), 2) self.assertEqual(attachments[0]["type"], "image/png") self.assertEqual(attachments[0]["name"], image_filename) self.assertEqual(decode_att(attachments[0]["data"]), image_data) self.assertEqual(attachments[1]["type"], "image/png") self.assertEqual(attachments[1]["name"], "") # unknown -- not attached as file self.assertEqual(decode_att(attachments[1]["data"]), image_data) # Make sure the image attachments are not treated as embedded: self.assertNotIn('inline_images', params)
def _build_multipart_msg(message, images): """Build Multipart message with in-line images.""" _LOGGER.debug('Building multipart email with embedded attachment(s)') msg = MIMEMultipart('related') msg_alt = MIMEMultipart('alternative') msg.attach(msg_alt) body_txt = MIMEText(message) msg_alt.attach(body_txt) body_text = ['<p>{}</p><br>'.format(message)] for atch_num, atch_name in enumerate(images): cid = 'image{}'.format(atch_num) body_text.append('<img src="cid:{}"><br>'.format(cid)) try: with open(atch_name, 'rb') as attachment_file: attachment = MIMEImage(attachment_file.read()) msg.attach(attachment) attachment.add_header('Content-ID', '<{}>'.format(cid)) except FileNotFoundError: _LOGGER.warning('Attachment %s not found. Skipping', atch_name) body_html = MIMEText(''.join(body_text), 'html') msg_alt.attach(body_html) return msg
def setUp(self): fp = openfile('PyBanner048.gif') try: self._imgdata = fp.read() finally: fp.close() self._im = MIMEImage(self._imgdata)
def test_checkSetMinor(self): im = MIMEImage(self._imgdata, 'fish') self.assertEqual(im.get_content_type(), 'image/fish')
def add_attachment(self,filepath,filename=None): if filename == None: filename=os.path.basename(filepath) with open(filepath,'rb') as f: file=f.read() 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": with open(filepath) as f:file=f.read() attachment = MIMEText(file, _subtype=subtype) elif maintype == "image": with open(filepath,'rb') as f:file=f.read() attachment = MIMEImage(file, _subtype=subtype) elif maintype == "audio": with open(filepath,'rb') as f:file=f.read() attachment = MIMEAudio(file, _subtype=subtype) else: with open(filepath,'rb') as f:file=f.read() attachment = MIMEBase(maintype,subtype) attachment.set_payload(file) attachment.add_header('Content-Disposition', 'attachment', filename=filename) encoders.encode_base64(attachment) attachment.add_header('Content-Disposition', 'attachment', filename=filename) attachment.add_header('Content-ID',str(self.attachment_num)) self.attachment_num+=1 self.attachment_list.append(attachment)
def get_attachments(self): # this returns two attachments, one a text file, the other an inline attachment that can be referred to in a # template using cid: notation fp = open('tests/python.jpeg', 'rb') img = MIMEImage(fp.read()) img.add_header('Content-ID', '<{}>'.format('python.jpg')) raw_data = 'Some Report Data' return [ ('Report.txt', raw_data, 'text/plain'), img, ]
def attach(outer, path): # 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': with open(path) as fp: # Note: we should handle calculating the charset msg = MIMEText(fp.read(), _subtype=subtype) elif maintype == 'image': with open(path, 'rb') as fp: msg = MIMEImage(fp.read(), _subtype=subtype) elif maintype == 'audio': with open(path, 'rb') as fp: msg = MIMEAudio(fp.read(), _subtype=subtype) else: with open(path, 'rb') as fp: msg = MIMEBase(maintype, subtype) msg.set_payload(fp.read()) # Encode the payload using Base64 encoders.encode_base64(msg) # Set the filename parameter msg.add_header('Content-Disposition', 'attachment', filename=path) outer.attach(msg)
def gmail(png_file): #add your gmail address and get your stored gmail password from keyring gmail_acct = "your_gmail address" #if you are not using keyring, comment out the text below app_spec_pwd = keyring.get_password("credentials", "gmail") #if you are not using keyring, uncomment the text below #app_spec_pwd = "your_gmail_password" #create variables for the "to" and "from" email addresses TO = ["email_address_of_receiver"] FROM = "email_address_of_sender" #asemble the message as "MIMEMultipart" mixed msg = MIMEMultipart('mixed') msg['Subject'] = 'Intruder Alert!' msg['From'] = FROM msg['To'] = ', '.join(TO) body = MIMEText('Motion was detected on your security camera.', 'plain') msg.attach(body) #open up an image file and attach it to the message img_data = open(png_file, 'rb') image = MIMEImage(img_data.read()) img_data.close() msg.attach(image) #open up the SMTP server, start a tls connection, login, send, and close server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.ehlo server.login(gmail_acct, app_spec_pwd) server.sendmail(FROM, TO, msg.as_string()) server.close()
def handle_trigger_event(self, sender, **data): # Retrieve the image buffer, and add the event image, if not there. images = self.get_image_buffer() event_image = data['image'] if event_image not in images: images = [event_image] + images # Create the container (outer) email message. msg = MIMEMultipart() msg['Subject'] = 'Camera %s, event: %s' % (data['source'], data['prediction']) # Set addresses msg['From'] = self.from_address msg['To'] = COMMASPACE.join(self.recipients) msg.preamble = msg['Subject'] for image in images: # Open the files in binary mode. Let the MIMEImage class automatically img = MIMEImage(image) msg.attach(img) # Send the email via our own SMTP server. s = smtplib.SMTP_SSL(self.smtp_server) s.sendmail(self.from_address, self.recipients, msg.as_string()) s.quit()