def getMIMEAudio(song):
    fp = open(SONG_PATH + song, 'rb')
    audioType = mimetypes.guess_type(SONG_PATH + song)
    audio = MIMEAudio(fp.read(),audioType[0].split('/')[1])
    fp.close()
    audio.add_header('Content-Disposition', 'attachment')
    audio.set_param('filename', song, header = 'Content-Disposition', charset = 'gb2312')

    return audio
예제 #2
0
def sendmail_2(from_addr, to_addr_list, cc_addr_list, subject, message, login, password, picfiles=[], audiofiles = [], otherfiles = [], smtpserver='smtp.163.com'):
	'Text mail with files'
	msg = MIMEMultipart()
	msg['Subject'] = subject
	msg['From'] = from_addr
	msg['To'] = ','.join(to_addr_list)
	msg['Cc'] = ','.join(cc_addr_list)

	text = MIMEText(message)
	msg.attach(text)
	for file in picfiles:
		fp = open(file, 'rb')
		mimetype, mimeencoding = mimetypes.guess_type(file)
		if mimeencoding or (mimetype is None):
			mimetype = "application/octet-stream"
		maintype, subtype = mimetype.split('/')
		img = MIMEImage(fp.read(), _subtype = subtype)
		fp.close()
		img.add_header("Content-Disposition","attachment",filename = file.split('\\')[-1])
		msg.attach(img)
	for file in audiofiles:
		fp = open(file, 'rb')
		mimetype, mimeencoding = mimetypes.guess_type(file)
		if mimeencoding or (mimetype is None):
			mimetype = "application/octet-stream"
		maintype, subtype = mimetype.split('/')
		audio = MIMEAudio(fp.read(), _subtype = subtype)
		fp.close()
		audio.add_header("Content-Disposition","attachment",filename = file.split('\\')[-1])
		msg.attach(audio)
	for file in otherfiles:
		fp = open(file, 'rb')
		mimetype, mimeencoding = mimetypes.guess_type(file)
		if mimeencoding or (mimetype is None):
			mimetype = "application/octet-stream"
		maintype, subtype = mimetype.split('/')
		other = MIMEBase(maintype, subtype)
		other.set_payload(fp.read())
		encoders.encode_base64(other)
		fp.close()
		other.add_header("Content-Disposition","attachment",filename = file.split('\\')[-1])
		msg.attach(other)

	server = smtplib.SMTP(smtpserver)
	server.starttls()
	server.login(login, password)
	problems = server.sendmail(from_addr, to_addr_list + cc_addr_list, msg.as_string())
	server.quit()
	return problems
예제 #3
0
 def composeMessage(email_from, email_to):
     if self.email_attach_flag:
         log.debug("getting mimetype for file: %s.wav" %self.file_loc)
         ctype, encoding = mimetypes.guess_type('%s.wav' % self.file_loc)
         log.debug("ctype: %s" % ctype)
         maintype, subtype = ctype.split('/', 1)
         file_loc = '%s.wav' % self.file_loc
         fp = open(file_loc, 'rb')
         msg = MIMEAudio(fp.read(), _subtype=subtype)
         fp.close()
         msg.add_header('Content-Disposition', 'attachment', filename = 'voicemail.wav')
         outer.attach(msg)
     composed = outer.as_string()
     s = smtplib.SMTP(smtp_server)
     x = s.sendmail(email_from, email_to, composed)
     x = s.quit()
     log.debug("Email sent")
예제 #4
0
def multipart():
    sender = '*****@*****.**'
    receiver = '*****@*****.**'
    subject = 'Faders up'
    body = 'I never should have moved out of Texsa. -J.\n'
    audio = 'kiss.mp3'

    m = MIMEMultipart()
    m['from'] = sender
    m['to'] = receiver
    m['subject'] = subject

    m.attach(MIMEText(body))
    apart = MIMEAudio(open(audio, 'rb').read(), 'mpeg')
    apart.add_header('Content-Disposition', 'attachment', filename=audio)
    m.attach(apart)

    s = smtplib.SMTP()
    s.connect(sender, [receiver], m.as_string())
    s.close()
예제 #5
0
def make_message(email):
    """ makes a python email.message.Message from our Email object """

    if email.body:
        # yes, yes, it's very ugly. It plays nice with content types such as: generic_type/specific_type; other_data
        specific_type = email.headers.get('Content-Type').split('/',1)[1].split(';',1)[0]
        msg = MIMEText(email.body, specific_type, 'utf-8')
    else:
    # this needs to go into a separate function
        msg = MIMEMultipart('alternative')
        # looks to see if a HTML and plaintext is there
        attachments = []
        for attachment in email.attachments.all():
            if attachment.content_type in ['text/plain', 'text/html']:
                attachments.append(attachment)

        for attachment in attachments:
            try:
                gen_type, specific_type = attachment.content_type.split('/', 1)
            except ValueError:
                gen_type, specific_type = 'application', 'octet-stream'
            msg.attach(MIMEText(attachment.data, specific_type))

        # okay now deal with other attachments
        for attachment in email.attachments.all():
            if attachment in attachments:
                continue # we've already handled it
            # right now deal with it
            try:
                gen_type, specific_type = attachment.content_type.split('/', 1)
            except (AttributeError, IndexError):
                gen_type, specific_type = 'application', 'octet-stream' # generic
            if gen_type == 'audio':
                attach = MIMEAudio(attachment.data, specific_type)
            elif gen_type == 'image':
                attach = MIMEImage(attachment.data, specific_type)
            elif gen_type == 'text':
                attach = MIMEText(attachment.data, specific_type, 'utf-8')
            else:
                attach = MIMEBase(gen_type, specific_type)
                attach.set_payload(attachment.data)
                encoders.encode_base64(attach)

            attach.add_header('Content-Disposition', 'attachment', filename=attachment.content_disposition)
            msg.attach(attach)

    # now add the headers
    for header in email.headers.all():
        msg[header.name] = header.data

    return msg
예제 #6
0
def main():
    parser = OptionParser(usage="""\
Send the contents of a directory as a MIME message.

Usage: %prog [options]

Unless the -o option is given, the email is sent by forwarding to your local
SMTP server, which then does the normal delivery process.  Your local machine
must be running an SMTP server.
""")
    parser.add_option('-d',
                      '--directory',
                      type='string',
                      action='store',
                      help="""Mail the contents of the specified directory,
                      otherwise use the current directory.  Only the regular
                      files in the directory are sent, and we don't recurse to
                      subdirectories.""")
    parser.add_option('-o',
                      '--output',
                      type='string',
                      action='store',
                      metavar='FILE',
                      help="""Print the composed message to FILE instead of
                      sending the message to the SMTP server.""")
    parser.add_option('-s',
                      '--sender',
                      type='string',
                      action='store',
                      metavar='SENDER',
                      help='The value of the From: header (required)')
    parser.add_option('-r',
                      '--recipient',
                      type='string',
                      action='append',
                      metavar='RECIPIENT',
                      default=[],
                      dest='recipients',
                      help='A To: header value (at least one required)')
    opts, args = parser.parse_args()
    if not opts.sender or not opts.recipients:
        parser.print_help()
        sys.exit(1)
    directory = opts.directory
    if not directory:
        directory = '.'
    # Create the enclosing (outer) message
    outer = MIMEMultipart()
    outer['Subject'] = 'Contents of directory %s' % os.path.abspath(directory)
    outer['To'] = COMMASPACE.join(opts.recipients)
    outer['From'] = opts.sender
    outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'

    for filename in os.listdir(directory):
        path = os.path.join(directory, filename)
        if not os.path.isfile(path):
            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(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)
            # Note: we should handle calculating the charset
            msg = MIMEText(fp.read(), _subtype=subtype)
            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)
            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=filename)
        outer.attach(msg)
    # Now send or store the message
    composed = outer.as_string()
    if opts.output:
        fp = open(opts.output, 'w')
        fp.write(composed)
        fp.close()
    else:
        s = smtplib.SMTP('localhost')
        s.sendmail(opts.sender, opts.recipients, composed)
        s.quit()
예제 #7
0
def create_Message_with_attachment(sender, to, subject, message_text_plain,
                                   message_text_html, attached_file):
    """Create a message for an email.

    message_text: The text of the email message.
    attached_file: The path to the file to be attached.

    Returns:
    An object containing a base64url encoded email object.
    """

    ##An email is composed of 3 part :
    #part 1: create the message container using a dictionary { to, from, subject }
    #part 2: attach the message_text with .attach() (could be plain and/or html)
    #part 3(optional): an attachment added with .attach()

    ## Part 1
    message = MIMEMultipart(
    )  #when alternative: no attach, but only plain_text
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject

    ## Part 2   (the message_text)
    # The order count: the first (html) will be use for email, the second will be attached (unless you comment it)
    message.attach(MIMEText(message_text_html, 'html'))
    message.attach(MIMEText(message_text_plain, 'plain'))

    ## Part 3 (attachment)
    # # to attach a text file you containing "test" you would do:
    # # message.attach(MIMEText("test", 'plain'))

    #-----About MimeTypes:
    # It tells gmail which application it should use to read the attachment (it acts like an extension for windows).
    # If you dont provide it, you just wont be able to read the attachment (eg. a text) within gmail. You'll have to download it to read it (windows will know how to read it with it's extension).

    #-----3.1 get MimeType of attachment
    #option 1: if you want to attach the same file just specify it’s mime types

    #option 2: if you want to attach any file use mimetypes.guess_type(attached_file)

    my_mimetype, encoding = mimetypes.guess_type(attached_file)

    # 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 unrecognized extension it set my_mimetypes to  'application/octet-stream' (so it won't return None again).
    if my_mimetype is None or encoding is not None:
        my_mimetype = 'application/octet-stream'

    main_type, sub_type = my_mimetype.split('/',
                                            1)  # split only at the first '/'
    # if my_mimetype is audio/mp3: main_type=audio sub_type=mp3

    #-----3.2  creating the attachment
    #you don't really "attach" the file but you attach a variable that contains the "binary content" of the file you want to attach

    #option 1: use MIMEBase for all my_mimetype (cf below)  - this is the easiest one to understand
    #option 2: use the specific MIME (ex for .mp3 = MIMEAudio)   - it's a shorcut version of MIMEBase

    #this part is used to tell how the file should be read and stored (r, or rb, etc.)
    if main_type == 'text':
        print("text")
        temp = open(
            attached_file, 'r'
        )  # 'rb' will send this error: 'bytes' object has no attribute 'encode'
        attachment = MIMEText(temp.read(), _subtype=sub_type)
        temp.close()

    elif main_type == 'image':
        print("image")
        temp = open(attached_file, 'rb')
        attachment = MIMEImage(temp.read(), _subtype=sub_type)
        temp.close()

    elif main_type == 'audio':
        print("audio")
        temp = open(attached_file, 'rb')
        attachment = MIMEAudio(temp.read(), _subtype=sub_type)
        temp.close()

    elif main_type == 'application' and sub_type == 'pdf':
        temp = open(attached_file, 'rb')
        attachment = MIMEApplication(temp.read(), _subtype=sub_type)
        temp.close()

    else:
        attachment = MIMEBase(main_type, sub_type)
        temp = open(attached_file, 'rb')
        attachment.set_payload(temp.read())
        temp.close()

    #-----3.3 encode the attachment, add a header and attach it to the message
    # encoders.encode_base64(attachment)  #not needed (cf. randomfigure comment)
    #https://docs.python.org/3/library/email-examples.html

    filename = os.path.basename(attached_file)
    attachment.add_header('Content-Disposition',
                          'attachment',
                          filename=filename)  # name preview in email
    message.attach(attachment)

    ## Part 4 encode the message (the message should be in bytes)
    message_as_bytes = message.as_bytes(
    )  # the message should converted from string to bytes.
    message_as_base64 = base64.urlsafe_b64encode(
        message_as_bytes)  #encode in base64 (printable letters coding)
    raw = message_as_base64.decode(
    )  # need to JSON serializable (no idea what does it means)
    return {'raw': raw}
예제 #8
0
    def send(self):
        """
        Send the email message represented by this object.
        """
        # Validate message
        if self._textBody is None and self._htmlBody is None:
            raise Exception(
                "Error! Must specify at least one body type (HTML or Text)")
        if len(self._to) == 0:
            raise Exception("Must specify at least one recipient")

        # Create the message part
        if self._textBody is not None and self._htmlBody is None:
            msg = MIMEText(self._textBody, "plain")
        elif self._textBody is None and self._htmlBody is not None:
            msg = MIMEText(self._htmlBody, "html")
        else:
            msg = MIMEMultipart("alternative")
            msg.attach(MIMEText(self._textBody, "plain"))
            msg.attach(MIMEText(self._htmlBody, "html"))
        # Add attachments, if any
        if len(self._attach) != 0:
            tmpmsg = msg
            msg = MIMEMultipart()
            msg.attach(tmpmsg)
        for fname, attachname in self._attach:
            if not os.path.exists(fname):
                print "File '%s' does not exist.  Not attaching to email." % fname
                continue
            if not os.path.isfile(fname):
                print "Attachment '%s' is not a file.  Not attaching to email." % fname
                continue
            # Guess at encoding type
            ctype, encoding = mimetypes.guess_type(fname)
            if ctype is None or encoding is not None:
                # No guess could be made so use a binary type.
                ctype = 'application/octet-stream'
            maintype, subtype = ctype.split('/', 1)
            if maintype == 'text':
                fp = open(fname)
                attach = MIMEText(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == 'image':
                fp = open(fname, 'rb')
                attach = MIMEImage(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == 'audio':
                fp = open(fname, 'rb')
                attach = MIMEAudio(fp.read(), _subtype=subtype)
                fp.close()
            else:
                fp = open(fname, 'rb')
                attach = MIMEBase(maintype, subtype)
                attach.set_payload(fp.read())
                fp.close()
                # Encode the payload using Base64
                encoders.encode_base64(attach)
            # Set the filename parameter
            if attachname is None:
                filename = os.path.basename(fname)
            else:
                filename = attachname
            attach.add_header('Content-Disposition',
                              'attachment',
                              filename=filename)
            msg.attach(attach)
        # Some header stuff
        msg['Subject'] = self._subject
        msg['From'] = self._from
        msg['To'] = ", ".join(self._to)
        server = smtplib.SMTP('smtp.comcast.net', 587)
        LOGIN = '******'
        PASSWORD = '******'
        server.set_debuglevel(1)
        server.ehlo()
        server.starttls()
        server.login(LOGIN, PASSWORD)
        msg.preamble = "You need a MIME enabled mail reader to see this message"
        # Send message
        msg = msg.as_string()
        #server = smtplib.SMTP(self._smtpServer)
        server.sendmail(self._from, self._to, msg)
        server.quit()
예제 #9
0
         # 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)
         # Note: we should handle calculating the charset
         msg = MIMEText(fp.read(), _subtype=subtype)
         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)
         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=filename)  # attachment para adjuntos regulares, inline para imágenes en el cuerpo del correo
     msg.add_header('Content-ID', '<'+filename+'>')  # Necesario para referenciar imágenes desde el cuerpo del correo
     outer.attach(msg)
 # Now send or store the message
 composed = outer.as_string()
 
    if ctype is None or encoding is not None:
        ctype = "application/octet-stream"

    maintype, subtype = ctype.split("/", 1)

    if maintype == "text":
        fp = open(fileToSend)
        attachment = MIMEText(fp.read(), _subtype=subtype)
        fp.close()
    elif maintype == "image":
        fp = open(fileToSend, "rb")
        attachment = MIMEImage(fp.read(), _subtype=subtype)
        fp.close()
    elif maintype == "audio":
        fp = open(fileToSend, "rb")
        attachment = MIMEAudio(fp.read(), _subtype=subtype)
        fp.close()
    else:
        fp = open(fileToSend, "rb")
        attachment = MIMEBase(maintype, subtype)
        attachment.set_payload(fp.read())
        fp.close()

    encoders.encode_base64(attachment)
    attachment.add_header("Content-Disposition",
                          "attachment",
                          filename=fileToSend)

    msg.attach(body)
    msg.attach(attachment)
예제 #11
0
def sendFile(emailto, file="results", text=""):
    # emails file to emailto address with designated filepath

    logStart("Sending file to %s " % emailto)
    date = datetime.today()

    # chooses which csv file to attach
    emailfrom = "Sovereign's Capital"
    if file == "manual":
        fileToSend = os.path.join(dir, "results/results-manual.csv")
        attachmentName = "ripple-twitter-%s-%s-%s.csv" % (date.year,
                                                          date.month, date.day)
    else:
        fileToSend = os.path.join(dir, "results/results.csv")
        attachmentName = "ripple-crunchbase-%s-%s-%s.csv" % (
            date.year, date.month, date.day)
    port = 25

    # MIME multipart settings to set from/to/subject
    msg = MIMEMultipart()
    msg["From"] = emailfrom
    msg["To"] = emailto
    msg["Subject"] = text
    msg.preamble = None

    ctype, encoding = mimetypes.guess_type(fileToSend)
    if ctype is None or encoding is not None:
        ctype = "application/octet-stream"

    maintype, subtype = ctype.split("/", 1)

    # options to send other assets if desired later
    if maintype == "text":
        fp = open(fileToSend)
        # Note: we should handle calculating the charset
        attachment = MIMEText(fp.read(), _subtype=subtype)
        fp.close()
    elif maintype == "image":
        fp = open(fileToSend, "rb")
        attachment = MIMEImage(fp.read(), _subtype=subtype)
        fp.close()
    elif maintype == "audio":
        fp = open(fileToSend, "rb")
        attachment = MIMEAudio(fp.read(), _subtype=subtype)
        fp.close()
    else:
        fp = open(fileToSend, "rb")
        attachment = MIMEBase(maintype, subtype)
        attachment.set_payload(fp.read())
        fp.close()
        encoders.encode_base64(attachment)
    attachment.add_header("Content-Disposition",
                          "attachment",
                          filename=attachmentName)
    msg.attach(attachment)

    # Uses gmail smtp settings; email/password are in config
    server = smtplib.SMTP("smtp.gmail.com:587")
    server.starttls()
    server.login(emailUsername, emailPassword)
    server.sendmail(emailfrom, emailto, msg.as_string())
    server.quit()

    logEnd("Done sending file")
예제 #12
0
def build_email(mail_to,
                subject,
                body_text,
                mail_from=u'*****@*****.**',
                reply_to=None,
                attachments=None,
                mime_headers=None):
    """
    Flexible Multipart MIME message builder.

    Implements message building using the "email" Python standard library
    https://docs.python.org/2/library/email-examples.html

    while following recommendations from
    https://stackoverflow.com/questions/3902455/smtp-multipart-alternative-vs-multipart-mixed

    .. seealso::

        - http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52243
        - http://mail.python.org/pipermail/tutor/1999-June/000259.html
        - http://www.bigbold.com/snippets/posts/show/2038
    """
    attachments = attachments or {}
    mime_headers = mime_headers or {}

    # ------------------------------------------
    #                envelope
    # ------------------------------------------

    message = MIMEMultipart('mixed')
    # TODO: Add text for non MIME-aware MUAs
    #message.preamble = 'You will not see this in a MIME-aware mail reader.\n'

    # Address headers
    address_headers = {
        'To': fix_addresslist(AddressList(mail_to)),
        'From': AddressList(mail_from),
        'Reply-To': AddressList(reply_to),
    }

    # Subject header
    mime_headers.update({u'Subject': Header(s=subject, charset='utf-8')})

    # Add address headers
    for key, item in address_headers.iteritems():
        if isinstance(item, AddressList):

            # v1
            #for address in format_addresslist(item):
            #    message[key] = address

            # v2
            value = ', '.join(format_addresslist(item))
            if value:
                message[key] = value

    # Add more headers
    for key, value in mime_headers.iteritems():
        #message.add_header(key, value)
        if value:
            message[key] = value

    # ------------------------------------------
    #              email body
    # ------------------------------------------
    body_message = MIMEMultipart('alternative')

    # Start off with a text/plain part
    # https://stackoverflow.com/questions/3902455/smtp-multipart-alternative-vs-multipart-mixed
    body_part1 = MIMEText(body_text, _subtype='plain', _charset='utf-8')
    #body_part1.set_payload(body_text)
    #body_part1.set_charset('utf-8')
    body_message.attach(body_part1)
    message.attach(body_message)

    # TODO: Add a text/html part
    #body_part2 = MIMEText(body_html, 'html')

    # ------------------------------------------
    #            multipart attachments
    # ------------------------------------------
    # from https://docs.python.org/2/library/email-examples.html
    for filename, payload in attachments.iteritems():

        # 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, strict=False)
        #print('ctype, encoding:', ctype, encoding)

        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)
        #print('maintype, subtype:', maintype, subtype)

        # Create proper MIME part by maintype
        if maintype == 'application' and subtype in ['xml', 'json']:
            part = MIMENonMultipart(maintype, subtype, charset='utf-8')
            part.set_payload(payload.encode('utf-8'), 'utf-8')

        elif maintype == 'text':
            part = MIMEText(payload.encode('utf-8'),
                            _subtype=subtype,
                            _charset='utf-8')
            #part.set_charset('utf-8')

        elif maintype == 'image':
            part = MIMEImage(payload, _subtype=subtype)
        elif maintype == 'audio':
            part = MIMEAudio(payload, _subtype=subtype)
        else:
            part = MIMEBase(maintype, subtype)
            part.set_payload(payload)
            # Encode the payload using Base64 (Content-Transfer-Encoding)
            encoders.encode_base64(part)

        #part = MIMEBase(maintype, subtype, _charset='utf-8')
        # replace forward slashes by dashes
        filename_attachment = filename.lstrip('/\\').replace('/', '-')
        part.add_header('Content-Disposition',
                        'attachment',
                        filename=filename_attachment.encode('utf-8'))
        #part.set_payload(payload.encode('utf-8'))
        #part.set_charset('utf-8')

        # Encode the payload using Base64 (Content-Transfer-Encoding)
        #encoders.encode_base64(part)

        # Add part to multipart message
        message.attach(part)

    payload = message.as_string()

    return payload
예제 #13
0
파일: __init__.py 프로젝트: sair770/ezgmail
def _createMessageWithAttachments(sender,
                                  recipient,
                                  subject,
                                  body,
                                  attachments,
                                  cc=None,
                                  bcc=None):
    """Creates a MIMEText object and returns it as a base64 encoded string in a {'raw': b64_MIMEText_object} dictionary, suitable for use by _sendMessage() and the
    users.messages.send(). File attachments can also be added to this message.

    `attachments` is a list of strings of filenames."""
    message = MIMEMultipart()
    message['to'] = recipient
    message['from'] = sender
    message['subject'] = subject
    if cc is not None:
        message['cc'] = cc
    if bcc is not None:
        message['bcc'] = bcc

    messageMimeTextPart = MIMEText(body, 'plain')
    message.attach(messageMimeTextPart)

    if isinstance(attachments, str):
        attachments = [attachments
                       ]  # If it's a string, put `attachments` in a list.

    for attachment in attachments:
        # Check that the file exists.
        if not os.path.exists(attachment):
            raise EZGmailException(
                '%r passed for attachment but %s does not exist.' %
                (attachment, os.path.abspath(attachment)))

        content_type, encoding = mimetypes.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, 'r')
            mimePart = MIMEText(fp.read(), _subtype=sub_type)
        else:
            fp = open(attachment, 'rb')
            if main_type == 'image':
                mimePart = MIMEImage(fp.read(), _subtype=sub_type)
            elif main_type == 'audio':
                mimePart = MIMEAudio(fp.read(), _subtype=sub_type)
            else:
                mimePart = MIMEBase(main_type, sub_type)
                mimePart.set_payload(fp.read())
        fp.close()

        filename = os.path.basename(attachment)
        mimePart.add_header('Content-Disposition',
                            'attachment',
                            filename=filename)
        message.attach(mimePart)

    return {
        'raw': base64.urlsafe_b64encode(message.as_bytes()).decode('ascii')
    }
예제 #14
0
    def attachment_handler(self, message, attachments):
        """
        Adds the attachments to the email message
        """
        for att in attachments:
            if att['maintype'] == 'text':
                msg_txt = MIMEText(att['data'], att['subtype'], 'utf-8')
                if att['cid'] is not None:
                    msg_txt.add_header('Content-Disposition',
                                       'inline',
                                       filename=att['name'])
                    msg_txt.add_header('Content-ID', '<' + att['name'] + '>')

                else:
                    msg_txt.add_header('Content-Disposition',
                                       'attachment',
                                       filename=att['name'])
                message.attach(msg_txt)

            elif att['maintype'] == 'image':
                msg_img = MIMEImage(att['data'], att['subtype'])
                if att['cid'] is not None:
                    msg_img.add_header('Content-Disposition',
                                       'inline',
                                       filename=att['name'])
                    msg_img.add_header('Content-ID', '<' + att['name'] + '>')

                else:
                    msg_img.add_header('Content-Disposition',
                                       'attachment',
                                       filename=att['name'])
                message.attach(msg_img)

            elif att['maintype'] == 'audio':
                msg_aud = MIMEAudio(att['data'], att['subtype'])
                if att['cid'] is not None:
                    msg_aud.add_header('Content-Disposition',
                                       'inline',
                                       filename=att['name'])
                    msg_aud.add_header('Content-ID', '<' + att['name'] + '>')

                else:
                    msg_aud.add_header('Content-Disposition',
                                       'attachment',
                                       filename=att['name'])
                message.attach(msg_aud)

            else:
                msg_base = MIMEBase(att['maintype'], att['subtype'])
                msg_base.set_payload(att['data'])
                if att['cid'] is not None:
                    msg_base.add_header('Content-Disposition',
                                        'inline',
                                        filename=att['name'])
                    msg_base.add_header('Content-ID', '<' + att['name'] + '>')

                else:
                    msg_base.add_header('Content-Disposition',
                                        'attachment',
                                        filename=att['name'])
                message.attach(msg_base)
    def send_Mail(self,
                  message_plain_text,
                  to,
                  sender='me',
                  subject=None,
                  attachments=None,
                  reply_message_id=None):
        '''
        Usage - 
        @send the mail to given address and attachments.
        Args - 
        @message_plain_text : the plain text body of the mail.
        @to : mail address that going to be delivered.
        @sender : default as `me`.
        @subject : the subject of the mail, when reply_message_id has been given, will auto substitute into that reply threads subject.
        @attachments : list of attachments that will going to be sent.
        @reply_message_id : id of the message that going to be replied.
        Return -
        @return the MIME object.
        '''
        message = MIMEMultipart()
        message['to'] = ' '.join(to)
        message['from'] = PROCESS_OWNER
        if reply_message_id:
            metadata = self.mail_service.users().messages().get(
                userId='me', id=reply_message_id, format='full').execute()
            threadId = metadata['threadId']
            message['In-Reply-To'] = reply_message_id
            message['References'] = reply_message_id
            for payload in metadata['payload']['headers']:

                if payload['name'] == 'Subject':
                    message['Subject'] = payload['value']

                else:
                    continue
        else:
            if not subject:
                print('''no subject provided for MIME''')
                return False
            else:
                message['subject'] = subject

        message.attach(MIMEText(message_plain_text, 'plain'))

        for attachment in attachments:
            if attachment:
                my_mimetype, encoding = mimetypes.guess_type(attachment)

                if my_mimetype is None or encoding is not None:
                    my_mimetype = 'application/octet-stream'
                main_type, sub_type = my_mimetype.split('/', 1)

                if main_type == 'text':
                    temp = open(attachment, 'r')
                    attachement = MIMEText(temp.read(), _subtype=sub_type)
                    temp.close()
                elif main_type == 'image':
                    temp = open(attachment, 'rb')
                    attachement = MIMEImage(temp.read(), _subtype=sub_type)
                    temp.close()

                elif main_type == 'audio':
                    temp = open(attachment, 'rb')
                    attachement = MIMEAudio(temp.read(), _subtype=sub_type)
                    temp.close()

                elif main_type == 'application' and sub_type == 'pdf':
                    temp = open(attachment, 'rb')
                    attachement = MIMEApplication(temp.read(),
                                                  _subtype=sub_type)
                    temp.close()

                else:
                    attachement = MIMEBase(main_type, sub_type)
                    temp = open(attachment, 'rb')
                    attachement.set_payload(temp.read())
                    temp.close()

                encoders.encode_base64(attachement)
                filename = os.path.basename(attachment)
                attachement.add_header(
                    'Content-Disposition', 'attachment',
                    filename=filename)  # name preview in email
                message.attach(attachement)
        print(message)
        ## Part 4 encode the message (the message should be in bytes)
        message_as_bytes = message.as_bytes(
        )  # the message should converted from string to bytes.
        message_as_base64 = base64.urlsafe_b64encode(
            message_as_bytes)  #encode in base64 (printable letters coding)
        raw = message_as_base64.decode(
        )  # need to JSON serializable (no idea what does it means)
        message = {'raw': raw}
        if reply_message_id:
            message['threadId'] = threadId
        try:
            message = self.mail_service.users().messages().send(
                userId=sender, body=message).execute()
            return message

        except (errors.HttpError):
            print('An error occurred: %s' % errors.HttpError)
예제 #16
0
    def create(self):
        if self.textBody is None and self.htmlBody is None:
            raiseExceptions("Error - must specify at least one body type")
        if len(self.to) == 0:
            raiseExceptions("Error - must specify at least one recipient")
        if self.textBody is not None and self.htmlBody is None:
            msg = MIMEText(self.textBody, "plain")
        elif self.textBody is None and self.htmlBody is not None:
            msg = MIMEText(self.htmlBody, "html")
        else:
            msg = MIMEMultipart("alternative")
            msg.attach(self.textBody, "plain")
            msg.attach(self.htmlBody, "html")
            if len(self.attach) != 0:
                tmpmsg = msg
                msg = MIMEMultipart()
                msg.attach(tmpmsg)
            for fname, attachname in self.attach:
                if not os.path.exists(fname):
                    print "File '%s' does not exist.  Not attaching to email." % fname
                    continue
                if not os.path.isfile(fname):
                    print "Attachment '%s' is not a file.  Not attaching to email." % fname
                    continue
            # Guess at encoding type
            ctype, encoding = mimetypes.guess_type(fname)
            if ctype is None or encoding is not None:
                # No guess could be made so use a binary type.
                ctype = 'application/octet-stream'
            maintype, subtype = ctype.split('/', 1)
            if maintype == 'text':
                fp = open(fname)
                attach = MIMEText(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == 'image':
                fp = open(fname, 'rb')
                attach = MIMEImage(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == 'audio':
                fp = open(fname, 'rb')
                attach = MIMEAudio(fp.read(), _subtype=subtype)
                fp.close()
            else:
                fp = open(fname, 'rb')
                attach = MIMEBase(maintype, subtype)
                attach.set_payload(fp.read())
                fp.close()
                # Encode the payload using Base64
                encoders.encode_base64(attach)

            # Set the filename parameter
            if attachname is None:
                filename = os.path.basename(fname)
            else:
                filename = attachname

            attach.add_header('Content-Disposition',
                              'attachment',
                              filename=filename)
            msg.attach(attach)
        if self.subject is not None:
            msg['Subject'] = self.subject
        if self.mailfrom is not None:
            msg['From'] = self.mailfrom
        if self.to is not None:
            msg['To'] = ", ".join(self.to)
        if self.messageID is not None:
            msg['Message-ID'] = self.messageID
        if self.date is not None:
            msg['Date'] = self.date
        msg.preamble = "You need a MIME enabled mail reader to see this message"
        return msg
예제 #17
0
    def send(self, recipients, sender="", subject="", message="", files=None, mimetype=None):
        """
        @param recipients: Recipients of the message
        @type recipients: mixed, string or list
        @param sender: Sender of the email
        @type sender: string
        @param subject: Subject of the email
        @type subject: string
        @param message: Body of the email
        @type message: string
        @param files: List of paths to files to attach
        @type files: list of strings
        @param mimetype: Type of the body plain, html or None for autodetection
        @type mimetype: string
        """
        if sender == "":
            sender = self._sender
        if isinstance(recipients, str):
            recipients = [recipients]
        server = smtplib.SMTP(self._server, self._port)
        server.ehlo()
        if self._ssl:
            server.starttls()
        if self._username:
            server.login(self._username, self._password)

        if mimetype is None:
            if '<html>' in message:
                mimetype = 'html'
            else:
                mimetype = 'plain'

        msg = MIMEText(message, mimetype)

        msg['Subject'] = subject
        msg['From'] = sender
        msg['To'] = ','.join(recipients)

        if files:
            txtmsg = msg
            msg = MIMEMultipart()
            msg['Subject'] = subject
            msg['From'] = sender
            msg['To'] = ','.join(recipients)
            msg.attach(txtmsg)
            for fl in files:
                # 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.
                filename = j.sal.fs.getBaseName(fl)
                ctype, encoding = mimetypes.guess_type(fl)
                content = j.sal.fs.fileGetContents(fl)
                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':
                    attachement = MIMEText(content, _subtype=subtype)
                elif maintype == 'image':
                    attachement = MIMEImage(content, _subtype=subtype)
                elif maintype == 'audio':
                    attachement = MIMEAudio(content, _subtype=subtype)
                else:
                    attachement = MIMEBase(maintype, subtype)
                    attachement.set_payload(content)
                    # Encode the payload using Base64
                    encoders.encode_base64(attachement)
                # Set the filename parameter
                attachement.add_header(
                    'Content-Disposition', 'attachment', filename=filename)
                msg.attach(attachement)
        server.sendmail(sender, recipients, msg.as_string())
        server.close()
예제 #18
0
def buildEmailMessage(from_url, to_url, msg=None,
                      subject=None, attachment_list=None,
                      extra_headers=None,
                      additional_headers=None):
  """
    Builds a mail message which is ready to be
    sent by Zope MailHost.

    * attachment_list is a list of dictionaries with those keys:
     - name : name of the attachment,
     - content: data of the attachment
     - mime_type: mime-type corresponding to the attachment
    * extra_headers is a dictionary of custom headers to add to the email.
      "X-" prefix is automatically added to those headers.
    * additional_headers is similar to extra_headers, but no prefix is added.
  """

  if attachment_list == None:
    # Create non multi-part MIME message.
    message = MIMEText(msg, _charset='utf-8')
    attachment_list = []
  else:
    # Create multi-part MIME message.
    message = MIMEMultipart()
    message.preamble = "If you can read this, your mailreader\n" \
                        "can not handle multi-part messages!\n"
    message.attach(MIMEText(msg, _charset='utf-8'))

  if extra_headers:
    for key, value in extra_headers.items():
      message.add_header('X-%s' % key, value)

  if additional_headers:
    for key, value in additional_headers.items():
      message.add_header(key, value)

  if subject:
    message.add_header('Subject',
                        make_header([(subject, 'utf-8')]).encode())
  if from_url:
    message.add_header('From', from_url)
  if to_url:
    message.add_header('To', to_url)

  for attachment in attachment_list:
    attachment_name = attachment.get('name', '')

    # try to guess the mime type
    if not attachment.has_key('mime_type'):
      mime_type, _ = guess_type( attachment_name )
      if mime_type is not None:
        attachment['mime_type'] = mime_type
      else:
        attachment['mime_type'] = 'application/octet-stream'

    # attach it
    if attachment['mime_type'] == 'text/plain':
      part = MIMEText(attachment['content'], _charset='utf-8')
    else:
      major, minor = attachment['mime_type'].split('/', 1)
      if major == 'text':
        part = MIMEText(attachment['content'], _subtype=minor)
      elif major == 'image':
        part = MIMEImage(attachment['content'], _subtype=minor)
      elif major == 'audio':
        part = MIMEAudio(attachment['content'], _subtype=minor)
      else:
        #  encode non-plaintext attachment in base64
        part = MIMEBase(major, minor)
        part.set_payload(attachment['content'])
        encoders.encode_base64(part)

    part.add_header('Content-Disposition', 'attachment',
                    filename=attachment_name)
    part.add_header('Content-ID', '<%s>' % \
                    ''.join(['%s' % ord(i) for i in attachment_name]))
    message.attach(part)

  return message
예제 #19
0
    def send(self,
             from_address,
             to_address: list,
             subject,
             message,
             content_type='plain',
             attachments=[]):

        if self.ssl == True:

            try:

                self.smtp.starttls()

            except smtplib.SMTPHeloError:

                self.txt_error = 'Error: cannot make HELO to this server'

                return False

            except RuntimeError:

                self.txt_error = 'Error: SSL/TLS is not supported in your python interpreter'

                return False

            except smtplib.SMTPException as e:

                self.txt_error = e.__str__()

                return False
            """
            except smtplib.SMTPNotSupportedError:
                
                self.txt_error='Error: SSL/TLS is not supported'
                
                return False
            """

        if self.username != '':

            try:

                self.smtp.login(self.username, self.password)

            except smtplib.SMTPHeloError:

                self.txt_error = 'Error: cannot make HELO to this server'

                return False

            except smtplib.SMTPAuthenticationError:

                self.txt_error = 'Error: cannot login. Wrong username or password'

                return False

            except smtplib.SMTPException:

                self.txt_error = 'Error: any method for login is avaliable'

                return False
            """
            except smtplib.SMTPNotSupportedError:
                
                self.txt_error='Error: AUTH is not supported'
                
                return False
            """

        COMMASPACE = ', '

        if len(attachments) == 0:

            msg = MIMEText(message, content_type)

            msg['Subject'] = subject
            msg['From'] = from_address

            msg['To'] = COMMASPACE.join(to_address)

            self.smtp.send_message(msg)

            #self.quit()

            return True

        else:

            outer = MIMEMultipart()

            outer['Subject'] = subject
            outer['From'] = from_address

            outer['To'] = COMMASPACE.join(to_address)

            # Attach message text

            msg = MIMEText(message, content_type)

            outer.attach(msg)

            for path in attachments:

                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=os.path.basename(path))

                outer.attach(msg)

            self.smtp.send_message(outer)

            #self.quit()

            return True
예제 #20
0
 GPIO.output(red_led, GPIO.LOW)
 
 
 #setup the message            
 subject = 'piframe ' + f_time
 log_file.write("stop recorded2\n")
 msg = MIMEMultipart()
 msg['Subject'] = subject
 msg['From'] = settings.me
 msg['To'] = settings.toaddr
 msg.preamble = "Audio @ " + f_time            
 log_file.write("stop recorded3\n")
 log_file.write(audio_filepathname)
 fp = open(audio_filepathname, 'rb')            
 log_file.write("stop recorded4\n")
 aud = MIMEAudio(fp.read())
 log_file.write("stop recorded5\n")
 fp.close()
 msg.attach(aud)
 log_file.write("stop recorded6\n")
 try:
     log_file.write("stop recorded7\n")
     s = smtplib.SMTP('smtp.gmail.com', 587)
     s.ehlo()
     s.starttls()
     s.ehlo()
     s.login(user=settings.me, password=settings.password)
     log_file.write("stop recorded8\n")
     s.sendmail(settings.me, settings.toaddr, msg.as_string())
     log_file.write("stop recorded9\n")
     s.quit()                               
예제 #21
0
def create_mime(data,maintype='text',subtype=None,charset=None,
    params={}, headers={}, encoding=None):
    """ create MIME message from data.
    if maintype is None, the default content type is text/plain for str,
     and application/octet-stream for binary data.
    The default charset and encoding are automatically detected.
    """
    from email.mime.base import MIMEBase
    from email.mime.application import MIMEApplication
    from email.mime.audio import MIMEAudio
    from email.mime.image import MIMEImage
    from email.mime.message import MIMEMessage
    from email.mime.text import MIMEText
    import email.encoders, six
    if maintype is None:
        if isinstance(data,(six.text_type,)+six.string_types):
            maintype= 'text'
        elif isinstance(data,six.binary_type):
            maintype,subtype = 'application', subtype or 'octet-stream'
    else:
        maintype = maintype.lower()
    cte = 'Content-Transfer-Encoding'
    if maintype=='text':
        subtype = subtype or 'plain'
        data, charset = check_charset(data,charset)
        if encoding is None:
            msg = MIMEText(data, subtype, charset)
        else:
            msg = MIMEText('', subtype, charset)
        if encoding in ('base64','quoted-printable'):
            del msg[cte]
            if not isinstance(data,six.binary_type): data = data.encode(charset)
            msg.set_payload(data)
            if encoding=='base64': email.encoders.encode_base64(msg)
            else: email.encoders.encode_quopri(msg)
        elif encoding:
            if six.PY3:
                from email.policy import default
                policy = default.clone(cte_type='8bit' if encoding=='8bit' else '7bit')
                msg.policy = policy
            msg.replace_header(cte,encoding)
            if encoding=='7bit' and charset!='us-ascii':
                raise UnicodeEncodeError
            if six.PY3 and isinstance(data,six.binary_type): data = data.decode(charset)
            msg.set_payload(data)
        if msg[cte]=='base64': # remove superflous newline
            data = msg.get_payload(decode=False)
            msg.set_payload(data.rstrip())
    else:
        idata = data if encoding else ''
        if maintype=='application': msg = MIMEApplication(idata, subtype, **params)
        elif maintype=='audio': msg = MIMEAudio(idata, subtype, **params)
        elif maintype=='image': msg = MIMEImage(idata, subtype, **params)
        elif maintype=='message': msg = MIMEMessage(idata, subtype)
        else:
            msg = MIMEBase(maintype, subtype, **params)
            encoding = encoding or 'base64'
        if encoding in ('base64','quoted-printable'):
            del msg[cte]
            msg.set_payload(data)
            if encoding=='base64': email.encoders.encode_base64(msg)
            else: email.encoders.encode_quopri(msg)
        elif encoding:
            if six.PY3:
                from email.policy import default
                policy = default.clone(cte_type='7bit' if encoding=='7bit' else '8bit')
                msg.policy = policy
            msg.replace_header(cte,encoding)
            if encoding=='7bit':
                if isinstance(data,six.string_types): data.encode('us-ascii')
                else: data.decode('us-ascii')
            if six.PY3 and isinstance(data,six.binary_type):
                data = data.decode('utf-8','surrogateescape')
            msg.set_payload(data)
        if msg[cte]=='base64': # remove superflous newline
            data = msg.get_payload(decode=False)
            msg.set_payload(data.rstrip())
    for k, v in six.iteritems(headers):
        _set_header(msg,k,v)
    return msg
예제 #22
0
파일: CI.py 프로젝트: eranyser/MyFirstApp
def send_mail(emailfrom='freeze', emailto='', emailcc='', subject=None, mesage='', attach=[], domain='@algotec.co.il'):
    """
    :param emailfrom:   - sender freeze by default
    :param emailto:     - mail list created from cfg file
    :param subject:     - mail subject
    :param mesage:      - body message
    :param attach:      - files attach
    :param domain:      - @algotec.co.il by default
    :return err:        - return error, exception of sendmail or 0 if not
    """

    emailto_list = []
    for u in emailto.split(','):
        if u == '' or u == ',':
            continue
        emailto_list.append('{}{}'.format(u.split('@')[0], domain))
    emailto_list = list(set(emailto_list))
    emailto = ','.join(emailto_list)
    join_mail = emailto_list

    if emailcc:
        emailcc_list = []
        for u in emailcc.split(','):
            if u == '' or u == ',':
                continue
            emailcc_list.append('{}{}'.format(u.split('@')[0], domain))
        emailcc_list = list(set(emailcc_list))
        emailcc = ','.join(emailcc_list)
        join_mail += emailcc_list

    emailfrom = '{}{}'.format(emailfrom, domain)

    msg = MIMEMultipart()
    msg["From"] = emailfrom
    msg["To"] = emailto
    if emailcc:
        msg["CC"] = emailcc
    if re.match('(ci_alert).*', emailfrom):
        msg['X-Priority'] = '2'
    msg["Subject"] = subject
    mesage = '{}\n\nThis is an automatically generated email'.format(mesage)
    html = """
    <html>
    <body>
    <pre style="font: monospace">
    {}
    </pre>
    </body>
    </html>
    """.format(mesage)

    foo = MIMEText(html, 'html')
    msg.attach(foo)

    if attach:
        for f in attach:
            ctype, encoding = mimetypes.guess_type(f)
            if ctype is None or encoding is not None:
                ctype = "application/octet-stream"

            maintype, subtype = ctype.split("/", 1)

            if maintype == "text":
                try:
                    fp = open(f)
                except IOError, e:
                    print "Error: %s" % e
                    continue
                # Note: we should handle calculating the charset
                attachment = MIMEText(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == "image":
                fp = open(f, "rb")
                attachment = MIMEImage(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == "audio":
                fp = open(f, "rb")
                attachment = MIMEAudio(fp.read(), _subtype=subtype)
                fp.close()
            else:
                fp = open(f, "rb")
                attachment = MIMEBase(maintype, subtype)
                attachment.set_payload(fp.read())
                fp.close()
                encoders.encode_base64(attachment)
            attachment.add_header("Content-Disposition", "attachment", filename=os.path.basename(f))
            msg.attach(attachment)
예제 #23
0
def email(subject, body, recipients, attachments):
    '''
    This functions sends a notification using Email
            Args:
            subject     (str) : Email Subject.
            body        (str) : Email Body.
            recipients  (str) : Email recipients.
            attachments (str) : Email attachments.
    '''
    click.echo('Sending out Email notification...')
    msg = MIMEMultipart()
    msg['From'] = simple_notifications_config.EMAIL_SENDER
    email_recipients = [recipients]
    msg['To'] = ', '.join(email_recipients)
    msg['Subject'] = subject
    msg.attach(MIMEText(body))

    if attachments is not None:
        attachments = attachments.split(',')
        for email_attachment in attachments:
            email_attachment = email_attachment.strip()
            ctype, encoding = mimetypes.guess_type(email_attachment)
            if ctype is None or encoding is not None:
                ctype = 'application/octet-stream'
            maintype, subtype = ctype.split('/', 1)
            if maintype == 'text':
                fp = open(email_attachment)
                # Note: we should handle calculating the charset
                attachments = MIMEText(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == 'image':
                fp = open(email_attachment, 'rb')
                attachments = MIMEImage(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == 'audio':
                fp = open(email_attachment, 'rb')
                attachments = MIMEAudio(fp.read(), _subtype=subtype)
                fp.close()
            else:
                fp = open(email_attachment, 'rb')
                attachments = MIMEBase(maintype, subtype)
                attachments.set_payload(fp.read())
                fp.close()
                encoders.encode_base64(attachments)
            attachments.add_header('Content-Disposition',
                                   'attachments',
                                   filename=email_attachment)
            msg.attach(attachments)

    server = smtplib.SMTP(simple_notifications_config.EMAIL_SERVER + ':' +
                          simple_notifications_config.EMAIL_SERVER_PORT)
    if simple_notifications_config.EMAIL_DEBUG_LEVEL == '1':
        server.set_debuglevel(1)
    server.starttls()
    server.login(simple_notifications_config.EMAIL_SENDER,
                 simple_notifications_config.EMAIL_PASSWORD)
    server.sendmail(simple_notifications_config.EMAIL_SENDER, email_recipients,
                    msg.as_string())
    server.quit()


# Uncomment these rows for manual testing
#if __name__ == '__main__':
#    notification()
예제 #24
0
    def send(self, recipent, filename='', subject="", message=""):
        # self.server.set_debuglevel(1)
        outer = MIMEMultipart('alternative')
        # outer['From'] = '<'+self.who+'>'
        outer['To'] = recipent
        outer['Subject'] = subject
        #outer['List-Unsubscribe'] = 'mailto:<unsubscribe@wikybetbonus>'
        print(outer.get('List-Unsubscribe'))
        msgAlternative = MIMEMultipart('alternative')
        msgText = MIMEText('This is the alternative plain text message.')
        msgAlternative.attach(msgText)
        outer.attach(msgAlternative)
        outer.attach(MIMEText(message, 'html'))


        print(self.who," ",recipent)
        for header in self.headers:
            outer.add_header(*header)
        if filename is not '':
            path = filename
            # dosyanın türünü tahmin edip ona göre type belirliyoruz
            ctype, encoding = mimetypes.guess_type(path)
            if ctype is None or encoding is not None:
                ctype = 'application/octet-stream'

            maintype, subtype = ctype.split('/', 1)
            if maintype == 'text':
                fp = open(path)
                msg = MIMEText(fp.read(), _subtype=subtype)
                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)
                msg.set_payload(fp.read())
                fp.close()
                """eğer yukarıdakilerden biri değilse mesajı base64 olarak encoded
                texte çevirip mesaja ekliyoruz"""
                # encoders.encode_base64(msg)

            msg.add_header('Content-Disposition', 'attachment', filename=filename)
            outer.attach(msg)

        # oluşturduğumuz text, html ve file datasını string olarak alıyoruz

        composed = outer.as_string()

        try:

            self.server.sendmail(self.who, [recipent], composed)
            Logger("Sender:{0} | Recipent:{1}, OK".format(self.who, recipent))

            return True


        except smtplib.SMTPAuthenticationError as hata:
            print("e-posta veya şifrenizi yanlış girdiniz.",
                  "orjinal hata iletisi: ", hata)
            raise smtplib.SMTPAuthenticationError(44, "444")
        except smtplib.SMTPConnectError as e:
            raise e
        except smtplib.SMTPSenderRefused as e:
            raise e
예제 #25
0
def gmail_sendmail(from_address,
                   password,
                   to_addresses,
                   cc_addresses,
                   bcc_addresses,
                   subject,
                   text_body='',
                   xhtml_body=None,
                   attachments=None):
    gmail_account = from_address
    if attachments == None:
        attachments = []
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login(gmail_account, password)
    outer = MIMEMultipart('mixed')
    outer['Subject'] = subject
    outer['To'] = ', '.join(to_addresses)
    if cc_addresses is not None:
        outer['Cc'] = ', '.join(cc_addresses)
    else:
        cc_addresses = []
    if bcc_addresses is None:
        bcc_addresses = []
    outer['From'] = from_address

    for att in attachments:
        if sys.platform == 'win32':
            if att[1] != ':':
                # relative path
                path = os.path.join(os.getcwd(), att)
            else:
                path = att
        elif sys.platform.startswith('linux') or \
                sys.platform in ('darwin', 'cygwin'):
            if att[0] != '/':
                # relative path
                path = os.path.join(os.getcwd(), att)
            else:
                path = att
        else:
            raise ValueError('what os is it?!')
        # 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, 'rb')
            # Note: we should handle calculating the charset
            msg = MIMEText(fp.read(), _subtype=subtype)
            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)
            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=os.path.basename(path))
        outer.attach(msg)

    if xhtml_body is not None:
        html_content = MIMEText(xhtml_body, 'html')
        outer.attach(html_content)
    else:
        text_content = MIMEText(text_body, 'plain')
        outer.attach(text_content)

    server.sendmail(gmail_account, to_addresses + cc_addresses + bcc_addresses,
                    outer.as_string())
    server.close()
예제 #26
0
    def addAttachments(self, mainmsg, bodytext, attaches, bodytextEncoding,
                       attachesEncodings):
        # add main text/plain part
        msg = MIMEText(bodytext, _charset=bodytextEncoding)
        mainmsg.attach(msg)

        # add attachment parts
        encodings = attachesEncodings or (['us-ascii'] * len(attaches))
        for (filename, fileencode) in zip(attaches, encodings):
            # filename maybe absolute or relative
            if not os.path.isfile(filename):
                continue
            # guess content type from file extension, ignore encoding
            contype, encoding = mimetypes.guess_type(filename)
            if contype is None or encoding is not None:
                contype = 'application/octet-stream'
            self.trace('Adding ' + contype)

            # build sub-message of appropriate kind
            maintype, subtype = contype.split('/', 1)
            if maintype == 'text':
                if fix_text_required(fileencode):
                    data = open(filename, 'r', encoding=fileencode)
                else:
                    data = open(filename, 'rb')
                msg = MIMEText(data.read(),
                               _subtype=subtype,
                               _charset=fileencode)
                data.close()

            elif maintype == 'image':
                data = open(filename, 'rb')
                msg = MIMEImage(data.read(),
                                _subtype=subtype,
                                _encoder=fix_encode_base64)
                data.close()

            elif maintype == 'audio':
                data = open(filename, 'rb')
                msg = MIMEAudio(data.read(),
                                _subtype=subtype,
                                _encoder=fix_encode_base64)
                data.close()

            elif maintype == 'application':
                data = open(filename, 'rb')
                msg = MIMEApplication(data.read(),
                                      _subtype=subtype,
                                      _encoder=fix_encode_base64)
                data.close()

            else:
                data = open(filename, 'rb')
                msg = MIMEBase(maintype, subtype)
                msg.set_payload(data.read())
                data.close()
                fix_encode_base64(msg)

            # set filename and attach to container
            basename = os.path.basename(filename)
            msg.add_header('Content-Disposition',
                           'attachment',
                           filename=basename)
            mainmsg.attach(msg)
예제 #27
0
	def sendmail(self):
		import mimetypes

		from optparse import OptionParser

		from email import encoders
		from email.message import Message
		from email.mime.audio import MIMEAudio
		from email.mime.base import MIMEBase
		from email.mime.image import MIMEImage
		from email.mime.multipart import MIMEMultipart
		from email.mime.text import MIMEText
		msg = MIMEMultipart()
		msg['To'] = ", ".join(self.to )
		msg['From'] = self.userName
		msg['Subject'] = self.subject

		body = self.message + "\n"

		for key,value in self.info.items():
			body = body + "\n\n" + key + ":"
			if isinstance(value, basestring):
				svalue = value.encode('ascii', 'ignore')
			else:
				svalue = str(value)
			if "\n" in svalue:
				body = body + "\n" + svalue
			else:
				body = body + " " + svalue
		self.body = body
		
		part = MIMEText(body, 'plain')
		msg.attach(part)

		for file in self.files:
			ctype, encoding = mimetypes.guess_type(file)
			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(file)
				# Note: we should handle calculating the charset
				attachment = MIMEText(fp.read(), _subtype=subtype)
				fp.close()
			elif maintype == 'image':
				fp = open(file, 'rb')
				attachment = MIMEImage(fp.read(), _subtype=subtype)
				fp.close()
			elif maintype == 'audio':
				fp = open(file, 'rb')
				attachment = MIMEAudio(fp.read(), _subtype=subtype)
				fp.close()
			else:
				fp = open(file, 'rb')
				attachment = MIMEBase(maintype, subtype)
				attachment.set_payload(fp.read())
				fp.close()
				# Encode the payload using Base64
				encoders.encode_base64(attachment)
			# Set the filename parameter
			attachment.add_header('Content-Disposition', 'attachment', filename=file)
			msg.attach(attachment)



		before = datetime.datetime.utcnow()

		
		if self.tls in [True,1,"1","True","TRUE","true","yes","Yes","YES"]:
			self.security = 'STARTTLS'
		if self.security.upper() in ['STARTTLS','TLS']:
			send = smtplib.SMTP(self.server, int(self.port))
			send.starttls()
		elif self.security.upper() in ['SSL','SSL/TLS']:
			send = smtplib.SMTP_SSL(self.server, self.port)
		else:
			send = smtplib.SMTP(self.server, int(self.port))
		send.login(str(self.userName), str(self.password))
		send.sendmail(str(self.userName),self.to, msg.as_string())
		send.quit()

		after = datetime.datetime.utcnow()
		delta = after - before
		self.duration = delta.total_seconds()
예제 #28
0
def compose_email(sender=None, receiver=None, message=None, subject=None, files2attach=None):
	# filenames unicode
	# file content binary or utf8
	# files2attach = [(filename, mimetype-or-None), ...]

	if message is None:
		raise ValueError('<message> is None, cannot compose email')

	message = message.lstrip().lstrip('\r\n').lstrip()

	if sender is None:
		sender = default_mail_sender

	if receiver is None:
		receiver = [default_mail_receiver]

	if subject is None:
		subject = 'compose_email() test'

	if files2attach is None:
		email = MIMEText(message, 'plain', 'utf8')
	else:
		email = MIMEMultipart()
		email.attach(MIMEText(message, 'plain', 'utf8'))

	email['From'] = sender
	email['To'] = ', '.join(receiver)
	email['Subject'] = subject

	if files2attach is None:
		return email

	for file2attach in files2attach:
		filename = file2attach[0]
		try:
			mimetype = file2attach[1]
		except IndexError:
			mimetype = gmMimeLib.guess_mimetype(filename = filename)
		# text/*
		if mimetype.startswith('text/'):
			txt = io.open(filename, mode = 'rt', encoding = 'utf8')
			attachment = MIMEText(txt.read(), 'plain', 'utf8')
			txt.close()
		# image/*
		elif mimetype.startswith('image/'):
			img = io.open(filename, mode = 'rb')
			attachment = MIMEImage(img.read())
			img.close()
		# audio/*
		elif mimetype.startswith('audio/'):
			song = io.open(filename, mode = 'rb')
			attachment = MIMEAudio(song.read())
			song.close()
		# catch-all application/*
		else:
			_log.debug('attaching [%s] with type [%s]', filename, mimetype)
			mime_subtype = mimetype.split('/', 1)[1]
			data = io.open(filename, mode = 'rb')
			attachment = MIMEApplication(data.read(), mime_subtype)
			data.close()

		try:
			attachment.replace_header('Content-Disposition', 'attachment; filename="%s"' % gmTools.fname_from_path(filename))
		except KeyError:
			attachment.add_header('Content-Disposition', 'attachment; filename="%s"' % gmTools.fname_from_path(filename))
		email.attach(attachment)

	return email
예제 #29
0
def _createMessageWithAttachments(sender,
                                  recipient,
                                  subject,
                                  body,
                                  attachments,
                                  cc=None,
                                  bcc=None):
    """Creates a MIMEText object and returns it as a base64 encoded string in a ``{'raw': b64_MIMEText_object}``
    dictionary, suitable for use by ``_sendMessage()`` and the ``users.messages.send()`` Gmail API. File attachments can
    also be added to this message.

    The ``sender``, ``recipient``, ``subject``, ``body`` arguments are strings.

    The ``attachments`` argument is a list of strings of filenames.

    The ``cc`` and ``bcc`` arguments are strings with comma-delimited email addresses.
    """
    message = MIMEMultipart()
    message["to"] = recipient
    message["from"] = sender
    message["subject"] = subject
    if cc is not None:
        message["cc"] = cc
    if bcc is not None:
        message["bcc"] = bcc

    messageMimeTextPart = MIMEText(body, "plain")
    message.attach(messageMimeTextPart)

    if isinstance(attachments, str):
        attachments = [attachments
                       ]  # If it's a string, put ``attachments`` in a list.

    for attachment in attachments:
        # Check that the file exists.
        if not os.path.exists(attachment):
            raise EZGmailException(
                "%r passed for attachment but %s does not exist." %
                (attachment, os.path.abspath(attachment)))

        content_type, encoding = mimetypes.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, "r")
            mimePart = MIMEText(fp.read(), _subtype=sub_type)
        else:
            fp = open(attachment, "rb")
            if main_type == "image":
                mimePart = MIMEImage(fp.read(), _subtype=sub_type)
            elif main_type == "audio":
                mimePart = MIMEAudio(fp.read(), _subtype=sub_type)
            else:
                mimePart = MIMEBase(main_type, sub_type)
                mimePart.set_payload(fp.read())
        fp.close()

        filename = os.path.basename(attachment)
        mimePart.add_header("Content-Disposition",
                            "attachment",
                            filename=filename)
        message.attach(mimePart)

    return {
        "raw": base64.urlsafe_b64encode(message.as_bytes()).decode("ascii")
    }
예제 #30
0
    def send_notification(self,
                          event,
                          alert,
                          template_name,
                          sender,
                          recipients,
                          recipients_cc=[],
                          recipients_bcc=[],
                          context={}):
        all_recipients = recipients + recipients_cc + recipients_bcc
        self.log.info(
            "Start trying to send notification to %s with event=%s of alert %s"
            % (str(all_recipients), event, alert))

        mail_template = self.get_email_template(template_name)
        if mail_template != False:
            self.log.debug(
                "Found template file (%s). Ready to send notification." %
                json.dumps(mail_template))

            # Parse html template with django
            try:
                # Parse body as django template
                template = self.env.get_template(
                    mail_template['template_file'])
                content = template.render(context)
                #self.log.debug("Parsed message body. Context was: %s" % (json.dumps(context)))

                text_content = strip_tags(content)

                # Parse subject as django template
                subject_template = Template(source=mail_template['subject'],
                                            variable_start_string='$',
                                            variable_end_string='$')
                subject = subject_template.render(context)
                self.log.debug("Parsed message subject: %s" % subject)

                # Prepare message
                self.log.debug("Preparing SMTP message...")
                msgRoot = MIMEMultipart('related')
                msgRoot['Subject'] = subject
                msgRoot['From'] = sender
                msgRoot['Date'] = formatdate(localtime=True)

                smtpRecipients = []
                msg = MIMEMultipart('alternative')
                msgRoot.attach(msg)

                #msg.preamble    = text_content

                if len(recipients) > 0:
                    smtpRecipients = smtpRecipients + recipients
                    msgRoot['To'] = COMMASPACE.join(recipients)
                if len(recipients_cc) > 0:
                    smtpRecipients = smtpRecipients + recipients_cc
                    msgRoot['CC'] = COMMASPACE.join(recipients_cc)

                if len(recipients_bcc) > 0:
                    smtpRecipients = smtpRecipients + recipients_bcc
                    msgRoot['BCC'] = COMMASPACE.join(recipients_bcc)

                # Add message body
                if mail_template['content_type'] == "html":
                    msg.attach(MIMEText(content, 'html'))
                else:
                    msg.attach(MIMEText(text_content, 'plain'))

                # Add attachments
                if 'attachments' in mail_template and mail_template[
                        'attachments'] != None and mail_template[
                            'attachments'] != "":
                    attachment_list = mail_template['attachments'].split(" ")
                    self.log.debug(
                        "Have to add attachments to this notification. Attachment list: %s"
                        % json.dumps(attachment_list))

                    for attachment in attachment_list or []:
                        local_file = os.path.join(
                            os.environ.get('SPLUNK_HOME'), "etc", "apps",
                            "alert_manager", "local", "templates",
                            "attachments", attachment)
                        default_file = os.path.join(
                            os.environ.get('SPLUNK_HOME'), "etc", "apps",
                            "alert_manager", "default", "templates",
                            "attachments", attachment)

                        attachment_file = None
                        if os.path.isfile(local_file):
                            attachment_file = local_file
                            self.log.debug(
                                "%s exists in local, using this one..." %
                                attachment)
                        else:
                            self.log.debug(
                                "%s not found in local folder, checking if there's one in default..."
                                % attachment)
                            if os.path.isfile(default_file):
                                attachment_file = default_file
                                self.log.debug(
                                    "%s exists in default, using this one..." %
                                    attachment)
                            else:
                                self.log.warn(
                                    "%s doesn't exist, won't add it to the message."
                                    % attachment)

                        if attachment_file != None:
                            ctype, encoding = mimetypes.guess_type(
                                attachment_file)
                            if ctype is None or encoding is not None:
                                ctype = "application/octet-stream"
                            maintype, subtype = ctype.split("/", 1)

                            msgAttachment = None
                            if maintype == "text":
                                try:
                                    fp = open(attachment_file)
                                    # Note: we should handle calculating the charset
                                    msgAttachment = MIMEText(fp.read(),
                                                             _subtype=subtype)
                                finally:
                                    fp.close()
                            elif maintype == "image":
                                try:
                                    fp = open(attachment_file, "rb")
                                    msgAttachment = MIMEImage(fp.read(),
                                                              _subtype=subtype)
                                finally:
                                    fp.close()
                            elif maintype == "audio":
                                try:
                                    fp = open(attachment_file, "rb")
                                    msgAttachment = MIMEAudio(fp.read(),
                                                              _subtype=subtype)
                                finally:
                                    fp.close()
                            else:
                                try:
                                    fp = open(attachment_file, "rb")
                                    msgAttachment = MIMEBase(maintype, subtype)
                                    msgAttachment.set_payload(fp.read())
                                    encoders.encode_base64(msgAttachment)
                                finally:
                                    fp.close()

                            if msgAttachment != None:
                                msgAttachment.add_header(
                                    "Content-ID", "<" +
                                    basename(attachment_file) + "@splunk>")
                                msgAttachment.add_header(
                                    "Content-Disposition",
                                    "attachment",
                                    filename=basename(attachment_file))
                                msgRoot.attach(msgAttachment)

                #self.log.debug("Mail message: %s" % msg.as_string())
                #self.log.debug("Settings: %s " % json.dumps(self.settings))
                self.log.debug("smtpRecipients: %s type: %s" %
                               (smtpRecipients, type(smtpRecipients)))
                self.log.info("Connecting to mailserver=%s ssl=%s tls=%s" %
                              (self.settings["MAIL_SERVER"],
                               self.settings["EMAIL_USE_SSL"],
                               self.settings["EMAIL_USE_TLS"]))
                if not self.settings["EMAIL_USE_SSL"]:
                    s = smtplib.SMTP(self.settings["MAIL_SERVER"])
                else:
                    s = smtplib.SMTP_SSL(self.settings["MAIL_SERVER"])

                if self.settings["EMAIL_USE_TLS"]:
                    s.starttls()

                if len(self.settings["EMAIL_HOST_USER"]) > 0:
                    s.login(str(self.settings["EMAIL_HOST_USER"]),
                            str(self.settings["EMAIL_HOST_PASSWORD"]))

                self.log.info("Sending emails....")
                s.sendmail(sender, smtpRecipients,
                           msgRoot.as_string().encode('utf-8'))
                s.quit()

                self.log.info("Notifications sent successfully")

            #except TemplateSyntaxError, e:
            #    self.log.error("Unable to parse template %s. Error: %s. Continuing without sending notification..." % (mail_template['template_file'], e))
            #except smtplib.SMTPServerDisconnected, e:
            #    self.log.error("SMTP server disconnected the connection. Error: %s" % e)
            except socket.error, e:
                self.log.error(
                    "Wasn't able to connect to mailserver. Reason: %s" % e)
            #except TemplateDoesNotExist, e:
            #    self.log.error("Template %s not found in %s nor %s. Continuing without sending notification..." % (mail_template['template_file'], local_dir, default_dir))
            except Exception as e:
                self.log.error(
                    "Unable to send notification. Continuing without sending notification. Unexpected Error: %s"
                    % (traceback.format_exc()))
예제 #31
0
파일: test_audio.py 프로젝트: ideascf/play
# coding=utf-8

from email.mime.audio import MIMEAudio

audio_data = ''
audio_msg = MIMEAudio(audio_data)
print audio_msg.as_string()
예제 #32
0
def create_message_with_attachment(
    sender, to, subject, message_text, file, cc = None):
  """Create a message for an email.

  Args:
    sender: Email address of the sender.
    to: Email address of the receiver.
    subject: The subject of the email message.
    message_text: The text of the email message.
    file: The path to the file to be attached.

  Returns:
    An object containing a base64url encoded email object.
  """
  message = MIMEMultipart()
  message['to'] = to
  if cc:
    message['cc'] = cc
  message['from'] = sender
  message['subject'] = subject

  msg = MIMEText(message_text)
  message.attach(msg)
  #for file in files:
  content_type, encoding = mimetypes.guess_type(file.name)

  fs = FileSystemStorage()
  fs.save(file.name, file)

  path = fs.path(file.name)

  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(path, 'rb')
      msg = MIMEText(fp.read(), _subtype=sub_type)
      fp.close()
  elif main_type == 'image':
      fp = open(path, 'rb')
      msg = MIMEImage(fp.read(), _subtype=sub_type)
      fp.close()
  elif main_type == 'audio':
      fp = open(path, 'rb')
      msg = MIMEAudio(fp.read(), _subtype=sub_type)

      fp.close()
  else:
      fp = open(path, 'rb')
      msg = MIMEBase(main_type, sub_type)
      msg.set_payload(fp.read())
      fp.close()

  fs.delete(file.name)

  filename = file.name
  msg.add_header('Content-Disposition', 'attachment', filename=filename)
  email.encoders.encode_base64(msg)
  message.attach(msg)

  return {'raw': base64.urlsafe_b64encode(message.as_string().encode('UTF-8')).decode('ascii')}
예제 #33
0
# Create the container (outer) email message.
msg = MIMEMultipart()
msg["Subject"] = "Voicemail"
# me == the sender's email address
# family = the list of all recipients' email addresses
msg["From"] = "*****@*****.**"
# msg['To'] = COMMASPACE.join(family)
msg["To"] = "*****@*****.**"
# msg.preamble = 'Our family reunion'

path = "test.mp3"
ctype, encoding = mimetypes.guess_type(path)
maintype, subtype = ctype.split("/", 1)

fp = open(path, "rb")
voice = MIMEAudio(fp.read(), _subtype=subtype)
fp.close()
voice.add_header("Content-Disposition", "attachment", filename="voice.mp3")
msg.attach(voice)

# Send the email via our own SMTP server.
s = smtplib.SMTP("localhost")
server.set_debuglevel(1)
s.sendmail(msg["From"], msg["To"], msg.as_string())
s.quit()

#
# import smtplib
#
# def prompt(prompt):
#    return raw_input(prompt).strip()
def generate_HTML_and_send_email(**kwargs):

    #Generate CSV data
    today = kwargs['execution_date'] + timedelta(days=1)
    today = today.strftime("%Y-%m-%d")
    cursor = presto.connect('presto.smartnews.internal',
                            port=8081,
                            username=OWNER).cursor()
    cursor.execute(csv_sql.format(execution_date=today))
    ret = cursor.fetchall()
    columns = [c[0] for c in cursor.description]
    df = pd.DataFrame(ret, columns=columns)
    #Removing JP FB ad accounts
    df = df[(df['campaign_name'] != 'CyberZ_facebook')
            & (df['campaign_name'] != 'SN_MP_DynamicAd_Grape_Articles')]
    global name
    name = 'master_network_data.csv'
    csv_file = df.to_csv(name, encoding='utf-8', index=False)

    create_yesterday_df(**kwargs)
    create_kpi_df(**kwargs)
    matured_kpi_df(**kwargs)

    html_v2 = """
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<meta charset="utf-8"/>
	<title><u>Yesterday's UA Performance</u></title>
	<style type="text/css" media="screen">
	table {
	    border: 1px solid black;
	    border-collapse: collapse;
	    border-spacing: 5px;
	    width:100%%;
	    text-align: center;
	    border-spacing: 2px;
	    padding: 5px;
	 }
	    
	th {
	    text-align: center;
	    background-color: #194196;
	    color: white;
	    height: 50px;
	 }
	 
	</style>
	</head>
	<html><body><h1><u>Yesterday's UA Performance</u></h1>
	<h2>Network Overview</h2>
	<table> 
	%s 
	</table>
	<h2>KPI Overview</h2>
	<table> 
	%s
	</table>
	<h2>Latest Matured D7 Weekly Cohort</h2>
	<table> 
	%s
	</table>
	<h2>Top DoD Spend Changes in Adsets </h2>
	<table> 
	%s
	</table>
	<h2>Best Campaigns by ROAS (using latest matured week data) </h2>
	<table> 
	%s
	</table>
	<h2>Worst Campaigns by ROAS (using latest matured week data) </h2>
	<table> 
	%s
	</table>
	</body></html>""" % (t, s, r, q, o, u)

    attachments = concat
    html_v3 = html_v2.encode('utf-8').strip()

    import smtplib
    import mimetypes
    import datetime
    from email.mime.multipart import MIMEMultipart
    from email import encoders
    from email.message import Message
    from email.mime.audio import MIMEAudio
    from email.mime.base import MIMEBase
    from email.mime.image import MIMEImage
    from email.mime.text import MIMEText

    now = datetime.datetime.now()
    emailfrom = '*****@*****.**'
    emailto = [
        '*****@*****.**', '*****@*****.**',
        '*****@*****.**', '*****@*****.**',
        '*****@*****.**', '*****@*****.**',
        '*****@*****.**', '*****@*****.**'
    ]
    fileToSend = name
    username = '******'
    password = Variable.get('us_marketing_email_secret')

    msg = MIMEMultipart()
    msg["From"] = emailfrom
    msg["To"] = ", ".join(emailto)
    msg["Subject"] = 'US Master Network Data - ' + str(today)
    msg.preamble = 'csv contained'

    body = html_v3
    msg.attach(MIMEText(body, 'html'))

    ctype, encoding = mimetypes.guess_type(fileToSend)
    if ctype is None or encoding is not None:
        ctype = "application/octet-stream"

    maintype, subtype = ctype.split("/", 1)

    if maintype == "text":
        fp = open(fileToSend)
        # Note: we should handle calculating the charset
        attachment = MIMEText(fp.read(), _subtype=subtype)
        fp.close()
    elif maintype == "image":
        fp = open(fileToSend, "rb")
        attachment = MIMEImage(fp.read(), _subtype=subtype)
        fp.close()
    elif maintype == "audio":
        fp = open(fileToSend, "rb")
        attachment = MIMEAudio(fp.read(), _subtype=subtype)
        fp.close()
    else:
        fp = open(fileToSend, "rb")
        attachment = MIMEBase(maintype, subtype)
        attachment.set_payload(fp.read())
        fp.close()
        encoders.encode_base64(attachment)
    attachment.add_header("Content-Disposition",
                          "attachment",
                          filename=fileToSend)
    msg.attach(attachment)

    server = smtplib.SMTP("smtp.gmail.com:587")
    server.starttls()
    server.login(username, password)
    server.sendmail(emailfrom, emailto, msg.as_string())
    server.quit()
예제 #35
0
def send_by_smtp(to=None,
                 cc=None,
                 bcc=None,
                 subject=None,
                 attachments=None,
                 attachment_type='plain'):
    """
        Snippet to send an email to multiple people along with multiple attachments.
        :param to: list of emails
        :param cc: list of emails
        :param bcc: list of emails
        :param subject: Email Subject
        :param attachments: list of file paths
        :param attachment_type: 'plain' or 'html'
        :return: None
    """
    email_from = sender_address
    email_to = list()
    files_to_send = attachments
    msg = MIMEMultipart()
    msg["From"] = email_from
    if to:
        to = list(set(to))
        email_to += to
        msg["To"] = ', '.join(to)
    if cc:
        cc = list(set(cc))
        email_to += cc
        msg["Cc"] = ', '.join(cc)
    if bcc:
        bcc = list(set(bcc))
        email_to += bcc
        msg["Bcc"] = ', '.join(bcc)
    if subject:
        msg["Subject"] = subject
        msg.preamble = subject
    else:
        msg["Subject"] = default_subject
        msg.preamble = default_subject

    body = default_message
    msg.attach(MIMEText(body, attachment_type))

    if files_to_send:
        for file_to_send in files_to_send:
            content_type, encoding = mimetypes.guess_type(file_to_send)
            if content_type is None or encoding is not None:
                content_type = "application/octet-stream"
            maintype, subtype = content_type.split("/", 1)
            if maintype == "text":
                with open(file_to_send) as fp:
                    # Note: we should handle calculating the charset
                    attachment = MIMEText(fp.read(), _subtype=subtype)
            elif maintype == "image":
                with open(file_to_send, "rb") as fp:
                    attachment = MIMEImage(fp.read(), _subtype=subtype)
            elif maintype == "audio":
                with open(file_to_send, "rb") as fp:
                    attachment = MIMEAudio(fp.read(), _subtype=subtype)
            else:
                with open(file_to_send, "rb") as fp:
                    attachment = MIMEBase(maintype, subtype)
                    attachment.set_payload(fp.read())
                encoders.encode_base64(attachment)
            attachment.add_header("Content-Disposition",
                                  "attachment",
                                  filename=ntpath.basename(file_to_send))
            msg.attach(attachment)

    try:
        smtp_obj = smtplib.SMTP(host=smtp_server_address,
                                port=smtp_port_number,
                                timeout=300)
        smtp_obj.sendmail(from_addr=email_from,
                          to_addrs=list(set([email_from] + email_to)),
                          msg=msg.as_string())
        print("Successfully sent email to {}".format(str(email_to)))
        smtp_obj.quit()
        return True
    except smtplib.SMTPException:
        print("Error: unable to send email")
        return False
예제 #36
0
    from StringIO import StringIO


ATTACH_FILE = "/tmp/foo.bar"
OUT_FILE = "/tmp/bar.foo"

#headers
msg = MIMEMultipart()
msg['To'] = '*****@*****.**'
msg['From'] = '*****@*****.**'
msg['Subject'] = "Test"
mime_msg['Date'] = formatdate(localtime=True) 

#text message
txtmsg = MIMEText('Please find attachment.')
msg.attach(txtmsg)

# attach file 
try:
    fp = open(ATTACH_FILE, )
    temp = MIMEAudio(fp.read())
    temp.add_header('content-disposition', 'attachment', filename=OUT_FILE)
    fp.close()
    msg.attach(temp)
except (Exception, e):
    print e

final_msg = StringIO(mime_msg.as_string())
#now send ur MIME message using `python/SMTP.py` or 'twisted/esmptFactory.py'

예제 #37
0
def createMail(sender, to, subject, message_html, files):
    """Create a message for an email.

  Args:
    sender: Email address of the sender.
    to: Email address of the receiver.
    subject: The subject of the email message.
    message_html: The text of the email message.
    files: The paths to the files to be attached.

  Returns:
    An object containing a base64url encoded email object.
  """
    try:
        message = MIMEMultipart()
        message['bcc'] = to
        message['from'] = sender
        message['subject'] = subject

        message.attach(MIMEText(message_html, 'html', 'utf-8'))

        if files[0] != '':
            for file in files:
                content_type, encoding = mimetypes.guess_type(file)

                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(file, 'rb')
                    msg = MIMEText(fp.read(), _subtype=sub_type)
                    fp.close()
                elif main_type == 'image':
                    fp = open(file, 'rb')
                    msg = MIMEImage(fp.read(), _subtype=sub_type)
                    fp.close()
                elif main_type == 'audio':
                    fp = open(file, 'rb')
                    msg = MIMEAudio(fp.read(), _subtype=sub_type)
                    fp.close()
                elif main_type == 'application':
                    fp = open(file, 'rb')
                    msg = MIMEApplication(fp.read(), _subtype=sub_type)
                    fp.close()
                else:
                    fp = open(file, 'rb')
                    msg = MIMEBase(main_type, sub_type)
                    msg.set_payload(fp.read())
                    fp.close()
                filename = os.path.basename(file)
                msg.add_header('Content-Disposition',
                               'attachment',
                               filename=filename)
                message.attach(msg)
    except Exception as e:
        logging.exception(e)
        return -1

    message_as_bytes = message.as_bytes(
    )  # the message should converted from string to bytes.
    message_as_base64 = base64.urlsafe_b64encode(
        message_as_bytes)  #encode in base64 (printable letters coding)
    raw = message_as_base64.decode(
    )  # need to JSON serializable (no idea what does it means)
    return {'raw': raw}
예제 #38
0
def send_mail(filename, to_addr):
    import smtplib
    import mimetypes
    import socks
    from email.mime.multipart import MIMEMultipart
    from email import encoders
    from email.message import Message
    from email.mime.audio import MIMEAudio
    from email.mime.base import MIMEBase
    from email.mime.image import MIMEImage
    from email.mime.text import MIMEText
    socks.setdefaultproxy(socks.HTTP, 'proxy.windstream.com', 8080)
    socks.wrapmodule(smtplib)

    emailto = to_addr  #"*****@*****.**"
    emailfrom = '*****@*****.**'
    fileToSend = filename

    msg = MIMEMultipart()
    msg["From"] = emailfrom
    msg["To"] = emailto
    msg["Subject"] = "CRQ Status Report for date " + str(Date_entry.get())
    msg.preamble = "CRQ Status Report"

    ctype, encoding = mimetypes.guess_type(fileToSend)
    if ctype is None or encoding is not None:
        ctype = "application/octet-stream"

    maintype, subtype = ctype.split("/", 1)

    if maintype == "text":
        fp = open(fileToSend)
        # Note: we should handle calculating the charset
        attachment = MIMEText(fp.read(), _subtype=subtype)
        fp.close()
    elif maintype == "image":
        fp = open(fileToSend, "rb")
        attachment = MIMEImage(fp.read(), _subtype=subtype)
        fp.close()
    elif maintype == "audio":
        fp = open(fileToSend, "rb")
        attachment = MIMEAudio(fp.read(), _subtype=subtype)
        fp.close()
    else:
        #with open(fileToSend,  'r', encoding='latin-1') as fp:
        fp = open(fileToSend, "rb")
        attachment = MIMEBase(maintype, subtype)
        attachment.set_payload(fp.read())
        fp.close()
        encoders.encode_base64(attachment)
    attachment.add_header("Content-Disposition",
                          "attachment",
                          filename=fileToSend)
    msg.attach(attachment)

    server = smtplib.SMTP("mailhost.windstream.com")
    #server.starttls()
    server.connect("mailhost.windstream.com")
    #server.login(username,password)
    try:
        server.sendmail(emailfrom, emailto, msg.as_string())
    except Exception as e:
        messagebox.showinfo('Error', str(e) + '\n' + 'Check To address')
    server.quit()