def email_file(self,filename=None,showname=None,img=None,body=None,subject=None,sendername=None): #此处直接定义一个发送图片+文件的方法 self.text_obj = multipart.MIMEMultipart() # 附件形式 # 添加一个文件 if filename: with open(filename, 'rb') as fo: fo_str = fo.read() attr = text.MIMEText(fo_str, _charset='utf-8') attr["Content-Type"] = 'application/octet-stream' if not showname: showname=os.path.basename(filename) # attr['Content-Disposition'] = 'attachment; filename=%s'%showname # 没有这个不显示附件位置··WWWW是名称,可以参数格式化 attr.add_header('Content-Disposition', 'attachment', filename=('gbk', '', showname)) self.text_obj.attach(attr) if not subject: subject='附件--%s'%showname if img and body: self.text_obj.attach(text.MIMEText(body, 'html', 'utf-8')) # 显示一个图片 with open(img, 'rb') as fo: im_str = fo.read() attr = image.MIMEImage(im_str) # attr.add_header('Content-ID', '<image1>') #指定图片 img_id = re.findall(r'cid:(\w+).*', body)[0] attr['Content-ID'] = '<%s>'%img_id # 这个是和body中的image1一致 self.text_obj.attach(attr) if not subject: subject='图片--%s'%(os.path.basename(img)) self.__email_conf(subject,sendername) self.__send_eamil()
def attach(filename): '''Elkészíti a MIME részt, benne a fájlnévvel''' if not os.path.isfile(filename): return None ctype, encoding = mimetypes.guess_type(filename) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) attachContent = open(filename, 'rb').read() if maintype == 'text': msg = text.MIMEText(attachContent, _subtype=subtype) elif maintype == 'image': msg = image.MIMEImage(attachContent, _subtype=subtype) elif maintype == 'audio': msg = audio.MIMEAudio(attachContent, _subtype=subtype) else: msg = base.MIMEBase(maintype, subtype) msg.set_payload(attachContent) encoders.encode_base64(msg) msg.add_header('Content-Disposition', 'attachment', filename=filename) return msg
def _handle_attachments(cls, outer, attachments): if type(attachments) == str: attrs = [attachments] elif type(attachments) == list: attrs = attachments else: attrs = [] for attached in attrs: if not os.path.isfile(attached): logger.warn('attached is not a file:%s' % attached) continue # 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(attached) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compressed) # use a generic bag-of-bits type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) try: if maintype == 'text': with open(attached, 'rb') as fhandle: # Note: we should handle calculating the charset msg = text.MIMEText( fhandle.read(), _subtype=subtype ) elif maintype == 'image': with open(attached, 'rb') as fhandle: imgid = os.path.basename(attached) msg = image.MIMEImage( fhandle.read(), _subtype=subtype ) msg.add_header('Content-ID', imgid) elif maintype == 'audio': with open(attached, 'rb') as fhandle: msg = audio.MIMEAudio(fhandle.read(), _subtype=subtype) else: with open(attached, 'rb') as fhandle: msg = base.MIMEBase(maintype, subtype) msg.set_payload(fhandle.read()) # Encode the payload using Base64 encoders.encode_base64(msg) # Set the filename parameter msg.add_header( 'Content-Disposition', 'attachment', filename=os.path.basename(attached) ) outer.attach(msg) # pylint: disable=W0703 except Exception as exception: logger.warn( 'failed to attach %s, errmsg:%s. Will skip it' % ( attached, str(exception) ) )
def SendMail(**kwargs): '''Sends an email :param str host: Address of smpt server :param str username: username for smtp account if required :param str password: password for smtp account if required :param str subject: subject for E-mail :param str message: text content of message :param str to: Recipient addresses as string or list of strings :param str cc: Recipient addresses as string or list of strings :param str from: Sender's E-mail address :param str fromFriendlyAddress: Nice looking Sender's E-mail address :param list files: comma delimited list of files to attach :param int port: port to use on server, default is 25 ''' host = kwargs.get('host', None) username = kwargs.get('username', None) password = kwargs.get('password', None) subject = kwargs.get('subject', "Build progress") toAddresses = kwargs.get('to', "") ccAddresses = kwargs.get('cc', "") fromAddress = kwargs.get('from', None) fromFriendlyAddress = kwargs.get('fromFriendlyAddress', "Build Script Pipeline") message = kwargs.get('message', "A build has completed.") files = (str(kwargs.get('files', []))).split(',') port = kwargs.get('port', 25) toAddressList = toAddresses ccAddressList = ccAddresses if isinstance(toAddresses, list): toAddressString = ', '.join(toAddresses) else: assert (isinstance(toAddresses, str)) toAddressString = toAddresses toAddressList = [toAddressList] if isinstance(ccAddresses, list): ccAddressString = ', '.join(ccAddresses) else: assert (isinstance(ccAddresses, str)) ccAddressString = ccAddresses ccAddressList = [ccAddressList] if len(toAddressString) == 0 and len(ccAddressString) == 0: prettyoutput.Log( 'No Email addresses specified for report, no report E-mailed.') return smtpConn = smtplib.SMTP(host, port) try: smtpConn.set_debuglevel(False) try: smtpConn.starttls() except: prettyoutput.Log("Could not start secure session") try: if (username is not None): smtpConn.login(username, password) except: prettyoutput.Log("Could not use provided credentials") # #Build the message # ConcatenatedToAddress = "" # if not toAddresses is None: # ConcatenatedToAddress = ','.join(toAddresses) # # ConcatenatedCCAddress = ','.join(ccAddresses) msg = multipart.MIMEMultipart() msg['Subject'] = subject msg['From'] = fromFriendlyAddress + ' [' + fromAddress + ']' msg['reply-to'] = fromAddress msg['To'] = toAddressString msg['cc'] = ccAddressString msg.attach(text.MIMEText(message)) if not files is None: for f in files: if not os.path.exists(f): prettyoutput.Log("Attachment Not found: " + f) continue hFile = open(f, 'rb') Data = hFile.read() hFile.close() hFile = None part = image.MIMEImage(Data) part.set_payload(Data) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment filename="%s"' % f) msg.attach(part) prettyoutput.Log("\nTo: " + toAddressString) prettyoutput.Log("\nCC: " + ccAddressString) prettyoutput.Log("Message:") prettyoutput.Log('\t' + message) AllRecipientAddresses = toAddressList + ccAddressList smtpConn.sendmail(fromAddress, AllRecipientAddresses, msg.as_string()) finally: smtpConn.quit()
def send_email(email_sender='me', email_to='', email_subject='', email_body_html='', email_cc='', email_bcc='', files=None): credentials = get_credentials() service = discovery.build(serviceName='gmail', version='v1', credentials=credentials) message = multipart.MIMEMultipart() message['to'] = email_to message['from'] = email_sender message['date'] = utils.formatdate(localtime=True) message['subject'] = email_subject message['cc'] = email_cc message['bcc'] = email_bcc message.attach(text.MIMEText(email_body_html, 'html')) for f in files or []: f = f.strip(' ') mimetype, encoding = mimetypes.guess_type(f) if mimetype is None or encoding is not None: mimetype = 'application/octet-stream' main_type, sub_type = mimetype.split('/', 1) if main_type == 'text': with open(f, 'rb') as outfile: attachement = text.MIMEText(outfile.read(), _subtype=sub_type) elif main_type == 'image': with open(f, 'rb') as outfile: attachement = image.MIMEImage(outfile.read(), _subtype=sub_type) elif main_type == 'audio': with open(f, 'rb') as outfile: attachement = audio.MIMEAudio(outfile.read(), _subtype=sub_type) elif main_type == 'application' and sub_type == 'pdf': with open(f, 'rb') as outfile: attachement = application.MIMEApplication(outfile.read(), _subtype=sub_type) else: attachement = base.MIMEBase(main_type, sub_type) with open(f, 'rb') as outfile: attachement.set_payload(outfile.read()) encoders.encode_base64(attachement) attachement.add_header('Content-Disposition', 'attachment', filename=os.path.basename(f)) message.attach(attachement) msg_bytes = message.as_bytes() print(f"Message size: {format_size(len(msg_bytes))}") media_body = http.MediaIoBaseUpload(io.BytesIO(msg_bytes), mimetype='message/rfc822', resumable=True) body_metadata = {} print('Sending...') try: response = service.users().messages().send( userId='me', body=body_metadata, media_body=media_body).execute() print(response) except errors.HttpError as error: print('Error:\n{}'.format(error))
def send_email(email_subject, email_body, email_sender='', email_to='', email_cc='', email_bcc='', files=None): # Pulling in the string value of the service key from the parameter with open(r'C:\Users\___.json') as f: service_account_info = json.loads(f.read()) # Define which scopes we're trying to access SCOPES = ['https://www.googleapis.com/auth/gmail.send'] # Setting up credentials using the gmail api credentials = service_account.Credentials.from_service_account_info( service_account_info, scopes=SCOPES) # This allows us to assign an alias account to the message so that the messages aren't coming from 'ServiceDriod-8328balh blah blah' delegated_credentials = credentials.with_subject(email_sender) # 'Building' the service instance using the credentials we've passed service = discovery.build(serviceName='gmail', version='v1', credentials=delegated_credentials) # Building out the email message = multipart.MIMEMultipart() message['to'] = email_to message['from'] = email_sender message['date'] = utils.formatdate(localtime=True) message['subject'] = email_subject message['cc'] = email_cc message['bcc'] = email_bcc message.attach(text.MIMEText(email_body, 'plain')) for f in files or []: f = f.strip(' ') mimetype, encoding = mimetypes.guess_type(f) # If the extension is not recognized it will return: (None, None) # If it's an .mp3, it will return: (audio/mp3, None) (None is for the encoding) # For an unrecognized extension we set mimetype to 'application/octet-stream' so it won't return None again. if mimetype is None or encoding is not None: mimetype = 'application/octet-stream' main_type, sub_type = mimetype.split('/', 1) # Creating the attachement: # This part is used to tell how the file should be read and stored (r, or rb, etc.) if main_type == 'text': print('text') with open(f, 'rb') as outfile: attachement = text.MIMEText(outfile.read(), _subtype=sub_type) elif main_type == 'image': print('image') with open(f, 'rb') as outfile: attachement = image.MIMEImage(outfile.read(), _subtype=sub_type) elif main_type == 'audio': print('audio') with open(f, 'rb') as outfile: attachement = audio.MIMEAudio(outfile.read(), _subtype=sub_type) elif main_type == 'application' and sub_type == 'pdf': with open(f, 'rb') as outfile: attachement = application.MIMEApplication(outfile.read(), _subtype=sub_type) else: attachement = base.MIMEBase(main_type, sub_type) with open(f, 'rb') as outfile: attachement.set_payload(outfile.read()) encoders.encode_base64(attachement) attachement.add_header('Content-Disposition', 'attachment', filename=os.path.basename(f)) message.attach(attachement) media_body = http.MediaIoBaseUpload(io.BytesIO(message.as_bytes()), mimetype='message/rfc822', resumable=True) body_metadata = {} # no thread, no labels in this example try: print('Uploading file...') response = service.users().messages().send( userId='me', body=body_metadata, media_body=media_body).execute() print(response) except errors.HttpError as error: print('An error occurred when sending the email:\n{}'.format(error))