Ejemplo n.º 1
0
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
Ejemplo n.º 2
0
 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)
                 )
             )
Ejemplo n.º 3
0
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))
Ejemplo n.º 4
0
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))