Пример #1
0
def load_attachment(filename, aka=None, encoding='utf-8'):
    r"""Read and wrap the ``filename`` into a proper MIME message
    """
    ctype, _encoding_ = mimetypes.guess_type(filename)
    if ctype:
        maintype, subtype = ctype.split('/', 1)
    else:               #   fail in guessing mime type
        maintype, subtype = 'application', 'octet-stream'
    if maintype == 'text':
        fp = open(filename)
        message = myMIMEText(fp.read(), subtype, encoding=encoding)
        del message['Content-Disposition']          # no inline for text attachment
        fp.close()
    elif maintype == 'image':
        fp = open(filename, 'rb')
        message = MIMEImage(fp.read(), _subtype=subtype)
        fp.close()
    elif maintype == 'audio':
        fp = open(filename, 'rb')
        message = MIMEAudio(fp.read(), _subtype=subtype)
        fp.close()
    else:
        fp = open(filename, 'rb')
        message = MIMEBase(maintype, subtype)
        message.set_payload(fp.read())
        fp.close()
        # Encode the payload using Base64
        encoders.encode_base64(message)
    if aka:                     # use aka instead of filename, if specified
        filename = aka
    message.add_header('Content-Disposition', 'attachment', filename=filename)
    return message
Пример #2
0
    def render_message(self, receiver: str, name: str):
        """
        creating message to send
        :param receiver:  person who received
        :param filename: photo to send
        :param html: html to send
        :return:
        """
        message = MIMEMultipart()
        message['From'] = self.sender
        message['To'] = receiver
        message['Subject'] = 'Your image'

        filename = self.change_photo_name(name)
        with open(filename, "rb") as attachment:
            part = MIMEImage("application", "octet-stream")
            part.set_payload(attachment.read())

        encoders.encode_base64(part)
        part.add_header(
            "Content-Disposition",
            f"attachment; filename= {filename}",
        )
        message.attach(part)
        html = self.create_html(name)
        message.attach(html)

        return message
Пример #3
0
    def attach(self,msg):
        for f in self.attachments:
        
            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 == "image":
                fp = open(f, "rb")
                attachment = MIMEImage(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == "text":
                fp = open(f)
                # Note: we should handle calculating the charset
                attachment = MIMEText(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=f)
            attachment.add_header('Content-ID', '<{}>'.format(f))
            msg.attach(attachment)
Пример #4
0
 def _add_attachments_to_msg(self, attachments: list = None, msg=None):
     if len(attachments) > 0:
         for filename in attachments:
             if os.path.dirname(filename) == "":
                 filename = str(Path.cwd() / filename)
             self.logger.debug("Adding attachment: %s", filename)
             with open(filename, "rb") as attachment:
                 _, ext = filename.lower().rsplit(".", 1)
                 if ext in IMAGE_FORMATS:
                     # image attachment
                     part = MIMEImage(
                         attachment.read(),
                         name=Path(filename).name,
                         _subtype=ext,
                     )
                 else:
                     # attach other filetypes
                     part = MIMEBase("application", "octet-stream")
                     part.set_payload(attachment.read())
                     encoders.encode_base64(part)
                 part.add_header(
                     "Content-Disposition",
                     f"attachment; filename= {Path(filename).name}",
                 )
                 msg.attach(part)
Пример #5
0
    def send(self, to_addr, name_replace=False):
        msg = MIMEMultipart()

        msg['From'] = self.header_format('시월의하늘준비모임', self.reply_addr)

        for entry in self.files:
            ctype, encoding = mimetypes.guess_type(entry)
            if ctype is None or encoding is not None:
                ctype = 'application/octet-stream'
            maintype, subtype = ctype.split('/', 1)

            with open(entry, 'rb') as fp:
                if maintype == 'image':
                    part = MIMEImage(fp.read(), _subtype=subtype)
                elif maintype == 'audio':
                    part = MIMEAudio(fp.read(), _subtype=subtype)
                else:
                    part = MIMEBase(maintype, subtype)
                    part.set_payload(fp.read())
                part.add_header('Content-Disposition',
                                'attachment',
                                filename=os.path.basename(entry))
                msg.attach(part)

        msg['Subject'] = Header(self.subject.format(name=to_addr["name"]),
                                'utf-8').encode('latin1')

        # 본문 이름 치환
        msg.attach(MIMEText(self.content.format(name=to_addr["name"]), 'html'))

        msg['To'] = self.header_format(to_addr["name"], to_addr["addr"])
        self.smtp.send_message(msg,
                               from_addr=self.reply_addr,
                               to_addrs=[to_addr["addr"]])
Пример #6
0
def attach_file(msg, path, c_name):
    # 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)
    with open(path, 'rb') as fp:
        bin_content = fp.read()
        if ctype in ['image/png', 'image/jpeg', 'image/jpg']:
            part = MIMEImage(bin_content, subtype)
        else:
            try:
                if bin_content.decode(
                ) == '# AUTO GENERATED ANSWER FOR NULL SUBMISSION':
                    return
                else:
                    part = MIMEBase(maintype, subtype)
                    part.set_payload(bin_content)
            except Exception as e:
                part = MIMEBase(maintype, subtype)
                part.set_payload(bin_content)

        part.add_header(
            'Content-Disposition', 'attachment; filename="{}"'.format(
                c_name if c_name is not None else path.split('/')[-1]))
        msg.attach(part)
def send_email_with_attachment(email_from, email_to, subject, smtp_ip_port, smtp_username, smtp_password, attachment_filename):
    """This function sends an email with an attachment using the provided credentials and filename """
    email = MIMEMultipart()
    email["From"] = email_from
    email["To"] = email_to
    email['Subject'] = subject
    email.preamble = email['Subject']

    content_type, encoding = mimetypes.guess_type(attachment_filename)
    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 == "image":
        file_pointer = open(attachment_filename, "rb")
        attachment = MIMEImage(file_pointer.read(), _subtype=sub_type)
        file_pointer.close()
    else:
        file_pointer = open(attachment_filename, "rb")
        attachment = MIMEBase(main_type, sub_type)
        attachment.set_payload(file_pointer.read())
        file_pointer.close()
        encoders.encode_base64(attachment)
    attachment.add_header("Content-Disposition", "attachment", filename=attachment_filename)
    email.attach(attachment)

    server = smtplib.SMTP(smtp_ip_port)
    server.starttls()
    server.login(smtp_username, smtp_password)
    server.sendmail(email_from, email_to, email.as_string())
    server.quit()
Пример #8
0
 def add_file(self, path):
     """check file exist
     """
     if not os.path.exists(path):
         raise IOError(f"please check file '{path}' exist")
     # Add attached file into mail
     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 == 'image':
         fp = open(path, 'rb')
         msg_file = MIMEImage(fp.read(), _subtype=subtype)
         fp.close()
     elif maintype == 'audio':
         fp = open(path, 'rb')
         msg_file = MIMEAudio(fp.read(), _subtype=subtype)
         fp.close()
     else:
         fp = open(path, 'rb')
         msg_file = MIMEBase(maintype, subtype)
         msg_file.set_payload(fp.read())
         fp.close()
         # Encode the payload using Base64
         encoders.encode_base64(msg_file)
     # Set the filename parameter
     msg_file.add_header('Content-Disposition', 'attachment', filename=path)
     self.attach.append(msg_file)
Пример #9
0
def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--subject', required=True)
    parser.add_argument('--from', required=True)
    parser.add_argument('--to', required=True)
    parser.add_argument('--configfile', type=argparse.FileType('r'), required=True, help='The .ini file with the mailserver credentials')
    parser.add_argument('--configsection', default='DEFAULT', help='The mail server section to choose in the configfile.')
    parser.add_argument('mailbody', metavar='MAILBODY', type=argparse.FileType('r'), help='A text file containing the mail body itself')
    parser.add_argument('attachments', metavar='ATTACHMENT', type=argparse.FileType('rb'), nargs='*', help='Optional files to attach')
    args = parser.parse_args()

    config = configparser.ConfigParser()
    config.sections()
    config.read_file(args.configfile)
    try:
        args.configsection
        config.items(args.configsection)
    except configparser.NoSectionError:
        print("Section {} not found in configfile {}.".format(args.configsection, args.configfile.name))

    add_charset('utf-8', QP, QP, 'utf-8')
    if len(args.attachments):
        msg = MIMEMultipart()
        msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'
        mime_parts = []
        msg.attach(MIMEText(args.mailbody.read(), _charset='utf-8'))
        args.mailbody.close()
        for attachment in args.attachments:
            ctype, encoding = mimetypes.guess_type(attachment.name)
            if ctype is None or encoding is not None:
                ctype = 'application/octet-stream'
            maintype, subtype = ctype.split('/', 1)
            if maintype == 'image':
                mime_part = MIMEImage(attachment.read(), _subtype=subtype)
            else:
                mime_part = MIMEBase(maintype, subtype)
                mime_part.set_payload(attachment.read())
                encoders.encode_base64(mime_part)
            attachment.close()
            mime_part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachment.name))
            msg.attach(mime_part)
    else:
        msg = MIMEText(args.mailbody.read(), _charset='utf-8')
        args.mailbody.close()
    
    msg['Subject'] = args.subject
    msg['From'] = getattr(args, 'from')
    msg['To'] = args.to

    server = smtplib.SMTP(config.get(args.configsection, 'server'), config.get(args.configsection, 'port'))
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login(config.get(args.configsection, 'username'), config.get(args.configsection, 'password'))

    server.send_message(msg)
    server.quit()
Пример #10
0
 def make_attachment(self, fn):
   data = open(fn, 'rb').read()
   ctype, encoding = mimetypes.guess_type(fn)
   maintype, subtype = (ctype or 'application/octet-stream').split('/', 1)
   if maintype == 'image':
     att = MIMEImage(data, _subtype=subtype)
   else:
     att = MIMEBase(maintype, subtype)
     att.set_payload(data)
     encoders.encode_base64(att)
   att.add_header('Content-Disposition', 'attachment',
                  filename=os.path.basename(fn))
   return att
Пример #11
0
 def make_attachment(self, fn):
   data = open(fn, 'rb').read()
   ctype, encoding = mimetypes.guess_type(fn)
   maintype, subtype = (ctype or 'application/octet-stream').split('/', 1)
   if maintype == 'image':
     att = MIMEImage(data, _subtype=subtype)
   else:
     att = MIMEBase(maintype, subtype)
     att.set_payload(data)
     encoders.encode_base64(att)
   att.add_header('Content-Disposition', 'attachment',
                  filename=os.path.basename(fn))
   return att
Пример #12
0
 def make_attachment(self, fn, filedata=None):
     if filedata and fn in filedata:
         data = filedata[fn]
     else:
         data = open(fn, "rb").read()
     ctype, encoding = mimetypes.guess_type(fn)
     maintype, subtype = (ctype or "application/octet-stream").split("/", 1)
     if maintype == "image":
         att = MIMEImage(data, _subtype=subtype)
     else:
         att = MIMEBase(maintype, subtype)
         att.set_payload(data)
         encoders.encode_base64(att)
     att.add_header("Content-Disposition", "attachment", filename=os.path.basename(fn))
     return att
Пример #13
0
    def add_file_to_outer(path):
        if not os.path.isfile(path):
            return

        # 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 == '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()
        elif maintype == 'text':
            # We do this to catch cases where text files have
            # an encoding we can't guess correctly.
            try:
                fp = open(path, 'r')
                msg = MIMEText(fp.read(), _subtype=subtype)
                fp.close()
            except UnicodeDecodeError:
                fp = open(path, 'rb')
                msg = MIMEBase(maintype, subtype)
                msg.set_payload(fp.read())
                encoders.encode_base64(msg)
                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)
Пример #14
0
    def as_msg(self):
        """return the mime msg.

        the results concrete type depends on the attachments mimetype.
        """
        maintype, subtype = self.mimetype.split('/')
        with open(self.path, 'rb') as fp:
            if maintype == 'image':
                msg = MIMEImage(fp.read(), _subtype=subtype)
            elif maintype == 'audio':
                msg = MIMEAudio(fp.read(), _subtype=subtype)
            else:
                msg = MIMEBase(maintype, subtype)
                msg.set_payload(fp.read())
                encoders.encode_base64(msg)

        msg.add_header('Content-Disposition',
                       'attachment',
                       filename=self.filename or os.path.basename(self.path))
        return msg
Пример #15
0
    def as_msg(self):
        """return the mime msg.

        the results concrete type depends on the attachments mimetype.
        """
        maintype, subtype = self.mimetype.split('/')
        with open(self.path, 'rb') as fp:
            if maintype == 'image':
                msg = MIMEImage(fp.read(), _subtype=subtype)
            elif maintype == 'audio':
                msg = MIMEAudio(fp.read(), _subtype=subtype)
            else:
                msg = MIMEBase(maintype, subtype)
                msg.set_payload(fp.read())
                encoders.encode_base64(msg)

        msg.add_header('Content-Disposition',
                       'attachment',
                       filename=self.filename or os.path.basename(self.path))
        return msg
Пример #16
0
def add_qr_and_link(index, url, text):
    #Create QR code and store as png alongside this script
    qr = pyqrcode.create(url)
    buffer = io.BytesIO()
    qr.png(buffer, scale=4)

    #Create text and link component of msg
    text_content = '<p>' + text + '<a href="' + url + '">' + url + '</a></p><p><img src="cid:' + index + '"></p>'
    #Create QR image component
    #img_content = MIMEBase('image', 'png', filename=qr_filename)
    img_content = MIMEImage(buffer.getvalue())
    # add required header data:
    #img_content.add_header('Content-Disposition', 'attachment', filename=qr_filename)
    img_content.add_header('X-Attachment-Id', index)
    img_content.add_header('Content-ID', '<' + index + '>')
    # read attachment file content into the MIMEBase object
    img_content.set_payload(buffer.getvalue())
    buffer.close()
    # encode with base64
    encoders.encode_base64(img_content)
    return [text_content, img_content]
Пример #17
0
def random_mail_body(file = '', pos = 0):
  msg = email.mime.Multipart.MIMEMultipart()
  msg["Subject"] = "Email test %s with id %s" %(os.path.basename(file), pos)
  msg["From"] = config["from"]
  msg["To"] = config["api_mail"]
  msg["Date"] = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" )
  body = email.mime.Text.MIMEText("""Hi, I am just test script. ignore me please""")
  msg.attach(body) 
  
  if file is "":
    file = random.choice(files)
  
  #msg["Subject"] += " From file "+ os.path.basename(file)
  
  ctype, coding = mimetypes.guess_type(file)
  
  maintype, subtype = ctype.split("/", 1)
  att = None
  if maintype == "image":
    fp = open(file, 'rb')
    att = MIMEImage(fp.read(), _subtype = subtype)
    fp.close()
  elif maintype == "audio":
    fp = open(file, "rb")
    att = MIMEAudio(fp.read(), _subtype = subtype)
    fp.close()
  else:
    fp = open(file, 'rb')
    att = MIMEBase(maintype, subtype)
    att.set_payload(fp.read())
    fp.close()
    # Encode the payload using Base64
    encoders.encode_base64(att)
    att.add_header('Content-Disposition', 'attachment; filename=%s' %(os.path.basename(file)))
    
  if att:
    msg.attach(att)
  print "File [%s] will be sent to server"  %(file)
  return msg.as_string()
Пример #18
0
def main(mailoptions):
    args = {}
    outer = MIMEMultipart()
    outer['Subject'] = mailoptions['subject']
    outer['To'] = COMMASPACE.join(mailoptions['recipients'])
    outer['From'] = mailoptions['sender']
    outer.preamble = mailoptions['message']

    ctype, encoding = mimetypes.guess_type(mailoptions['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(mailoptions['path']) as fp:
            print(fp.read())
            # msg = MIMEText(fp.read(), _subtype=subtype)
    elif maintype == 'image':
        with open(mailoptions['path'], 'rb') as fp:
            msg = MIMEImage(fp.read(), _subtype=subtype)
    else:
        with open(mailoptions['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=mailoptions.filename)
    outer.attach(msg)
    # Now send or store the message
    composed = outer.as_string()

    with smtplib.SMTP(mailoptions['host'], mailoptions['port']) as s:
        s.login(mailoptions['from_addr'], mailoptions['password'])
        s.sendmail(mailoptions['sender'], mailoptions['recipients'], composed)
Пример #19
0
    def send_mail(self):
        msg = MIMEMultipart()
        msg["From"] = self.email_fromaddr
        msg["To"] = self.email_toaddr
        msg["Subject"] = self.subject

        msg.attach(MIMEText(self.text))

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

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

            if maintype == "image":
                fp = open(self.file_to_send, "rb")
                attachment = MIMEImage(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == "audio":
                fp = open(self.file_to_send, "rb")
                attachment = MIMEAudio(fp.read(), _subtype=subtype)
                fp.close()
            else:
                fp = open(self.file_to_send, "rb")
                attachment = MIMEBase(maintype, subtype)
                attachment.set_payload(fp.read())
                fp.close()
                encoders.encode_base64(attachment)
            attachment.add_header("Content-Disposition", "attachment", filename=self.file_to_send)
            msg.attach(attachment)

        smtp = smtplib.SMTP(self.server)
        smtp.starttls()
        smtp.login(self.email_user, self.email_pw)
        smtp.sendmail(self.email_fromaddr, self.email_toaddr, msg.as_string())
        smtp.close()
        print "PiSN: Email sent to {0}".format(self.email_toaddr)
Пример #20
0
def sendMail(subject, content, sender, receivers, attachments=None):
    """Send email to one or more email addresses, attachment is optional"""
    outer = MIMEMultipart()
    outer["Subject"] = str(subject)
    outer["From"] = sender
    outer["BCC"] = ", ".join(receivers)
    outer.attach(MIMEText(content, 'html'))

    if attachments:
        for attachment_name, attachment in attachments.iteritems():
            file_name = attachment.split('/')[-1]
            ctype, encoding = mimetypes.guess_type(attachment)
            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 == 'image':
                fp = open(attachment, 'rb')
                msg = MIMEImage(fp.read(), _subtype=subtype)
                fp.close()
            else:
                fp = open(attachment, 'rb')
                msg = MIMEBase(maintype, subtype)
                msg.set_payload(fp.read())
                fp.close()
                # Encode the payload using Base64
                encoders.encode_base64(msg)

            msg.add_header('Content-Disposition',
                           'attachment',
                           filename=file_name)
            msg.add_header('Content-ID', '<{}>'.format(attachment_name))
            outer.attach(msg)

    s = smtplib.SMTP("localhost")
    s.sendmail(sender, receivers, outer.as_string())
    s.quit()
Пример #21
0
    def send(self, recipients, subject="", body="", filename=None):
        msg = MIMEMultipart()
        if not self._username or not self._userpass:
            raise UserInfoError()

        if isinstance(recipients, str):
            recipients = [recipients]

        msg['From'] = self._username
        msg['To'] = self.COMMASPACE.join(recipients)

        if subject == "":
            msg['Subject'] = self._subject
        else:
            msg['Subject'] = subject

        if body == "":
            body = self._body
        else:
            body = MIMEText(body)

        msg.attach(body)

        if filename is not None:
            import os
            import mimetypes

            file_basename = os.path.basename(filename)
            ctype, encoding = mimetypes.guess_type(filename)

            if ctype is None or encoding is not None:
                ctype = 'application/octet-stream'
            maintype, subtype = ctype.split('/')

            if maintype == 'image':
                from email.mime.image import MIMEImage
                with open(filename, 'rb') as fp:
                    part = MIMEImage(fp.read(), _subtype=subtype)
            else:
                from email.mime.base import MIMEBase
                from email import encoders
                with open(filename, 'rb') as fp:
                    part = MIMEBase(maintype, subtype)
                    part.set_payload(fp.read())
                encoders.encode_base64(part)
            part.add_header('Content-Disposition',
                            'attachment',
                            filename=file_basename)
            msg.attach(part)

        try:
            self._initialize()
            self._sendmail(recipients, msg)
        except smtplib.SMTPAuthenticationError as e:
            print(str(e))
        except smtplib.SMTPConnectError as e:
            print(str(e))
        except smtplib.SMTPServerDisconnected as e:
            print(str(e))
            self._server = None
            self._initialize()
            self._sendmail(recipients, msg)
        except smtplib.SMTPException as e:
            print(str(e))
        else:
            print("Sent mail from %s to %s, Success!!" %
                  (self._username, recipients))
Пример #22
0
 def set_image_payload(self):
 	submission = MIMEImage('image', '{}'.format(self.image_format))
 	submission.set_payload(open(self.image_path, 'rb').read())
 	self.related.attach(submission)
Пример #23
0
def send_mail(host, user, password, to_list, **kwargs):
    """
    发邮件
    :param {string} host: 连接smtp服务器
    :param {string} user: 登陆账号
    :param {string} password: 登陆密码
    :param {list} to_list: 收信人列表, 如: ["收件人1 <*****@*****.**>", "*****@*****.**"]

    :param {int} port: 连接smtp服务器的端口号,默认是 25
    :param {bool} use_ssl: 是否使用 ssl 协议连接smtp服务器, 使用之后的默认端口是 465
    :param {string} From: 收到信时显示的发信人设置,如:"测试邮件<*****@*****.**>"
    :param {string} Cc: 抄送人, 多人用英文逗号分开, 如:"[email protected], [email protected]"
    :param {string} BCc: 暗抄邮箱(有抄送效果,但抄送人列表不展示), 多人用英文逗号分开, 如:"[email protected], [email protected]"
    :param {string} Subject: 邮件主题
    :param {string} html: HTML 格式的邮件正文内容
    :param {string} text: 纯文本 格式的邮件正文内容(html格式的及纯文本格式的,只能传其中一个,以html参数优先)
    :param {list} files: 附件列表,需填入附件路径,或者文件名及文件二进制流,如:["d:\\123.txt"]
                         或者 [{"file_content":open("d:\\123.txt", 'rb').read(), "file_name":"123.txt"}]
    :return {bool}: 发信成功则返回 True,否则返回 False
    """
    # 添加邮件内容
    msg = MIMEMultipart()
    msg['Date'] = formatdate(localtime=True)

    # 发信人
    from_address = to_str(kwargs.get('From'))
    msg['From'] = from_address

    # 邮件主题
    Subject = kwargs.get('Subject')
    if Subject:
        msg['Subject'] = Header(to_str(Subject), 'utf-8')  # 转编码,以免客户端看起来是乱码的

    # 邮件正文内容
    html = kwargs.get('html')
    text = kwargs.get('text')
    # HTML 格式的邮件正文内容
    if html:
        html = to_str(html)
        msg.attach(MIMEText(html, _subtype='html', _charset='utf-8'))
    # 纯文本 格式的邮件正文内容
    elif text:
        text = to_str(text)
        msg.attach(MIMEText(text, _subtype='plain', _charset='utf-8'))

    # 收信人列表
    if isinstance(to_list, basestring):
        to_list = [to_list]
    assert type(to_list) == list
    to_address = [to_str(to) for to in to_list]
    msg['To'] = COMMASPACE.join(
        to_address)  # COMMASPACE==', '  # 收件人邮箱, 多人逗号分开

    # 抄送人, 多人用英文逗号分开
    cc_address = kwargs.get('Cc')
    if cc_address:
        msg['Cc'] = to_str(cc_address)
    # 暗抄邮箱, 多人用英文逗号分开
    bcc_address = kwargs.get('BCc')
    if bcc_address:
        msg['BCc'] = to_str(bcc_address)

    # 添加附件
    if 'files' in kwargs:
        files = kwargs.get('files') or []
        index = 0
        for file_path in files:
            if isinstance(file_path, basestring):
                # 文件路径
                file_path = to_unicode(file_path)
                # 文件内容
                file_content = open(file_path, 'rb').read()
                # 文件名(不包含路径)
                file_name = os.path.basename(file_path)
            # 传过来文件二进制流
            elif isinstance(file_path, dict):
                file_content = file_path['file_content']
                file_name = file_path['file_name']

            # 取文件后缀
            suffix = file_name.split('.')[-1]
            suffix = suffix.lower()
            # 处理图片附件
            if suffix in IMAGE_TYPES:
                index += 1
                mime = MIMEImage(file_content)
                mime.add_header('Content-ID', '<image%d>' % index)
                mime.add_header('Content-Type',
                                TYPE_NAME.get(suffix, "image/" + suffix))
            # 传送 txt 文件
            elif suffix == 'txt':
                mime = MIMEText(file_content,
                                _subtype='base64',
                                _charset='utf-8')
                mime["Content-Type"] = 'application/octet-stream'
            # 其它附件
            else:
                mime = MIMEBase('application',
                                'octet-stream')  # 'octet-stream': binary data
                mime.set_payload(file_content)
                encoders.encode_base64(mime)
            set_file_name(mime, file_name)
            msg.attach(mime)

    # 发送邮件
    try:
        use_ssl = kwargs.get('use_ssl')
        port = kwargs.get('port')
        if use_ssl:
            port = port or 465
            smtp = smtplib.SMTP_SSL()
        else:
            port = port or 25
            smtp = smtplib.SMTP()
        smtp.connect(host, port)  # 连接 smtp 服务器
        smtp.login(user, password)  # 登陆服务器
        smtp.sendmail(from_address, to_address, msg.as_string())  # 发送邮件
        # smtp.close()
        smtp.quit()

        return True
    except smtplib.SMTPException as err:
        logger.error('发邮件出现 SMTPException 错误: %s', err, exc_info=True)
        return False
    except Exception as e:
        logger.error('发邮件错误:%s', e, exc_info=True)
        return False
Пример #24
0
def send_email(to_list,
               cc_list,
               bcc_list,
               subject,
               mimetype_parts_dict,
               mailServer=None,
               attach=None,
               from_user=None,
               reply_to=None,
               attach_multi=None,
               log=None,
               image=None,
               image_multi=None):
    msg = MIMEMultipart()
    from_user = cc.credentials['gmail']
    msg['From'] = from_user['user']
    password = from_user['password']
    gmail_server = from_user['server']
    port = from_user['port']

    if reply_to is not None:
        msg['reply-to'] = reply_to
    msg['To'] = ",".join(to_list)
    msg['CC'] = ",".join(cc_list)
    msg['Subject'] = subject
    if mailServer is None:
        print('Non init mailServer')
        mailServer = init_mailServer(gmail_server, password, msg, port)
    'Attaching different parts of Message (eg, text, plain, html etc)'
    for parts in mimetype_parts_dict:
        attaching_part = MIMEText(mimetype_parts_dict[parts], parts)
        msg.attach(attaching_part)
    'Attaching images'
    if image is not None:
        try:
            part = MIMEImage(open(image, 'rb').read())
            part.add_header('Content-ID', '<%s>' % os.path.basename(image))
            msg.attach(part)
        except:
            pass
    'For Multiple Images'
    if image_multi is not None and len(image_multi) > 0:
        for image in image_multi:
            try:
                part = MIMEImage(open(image, 'rb').read())
                part.add_header('Content-ID', '<%s>' % os.path.basename(image))
                msg.attach(part)
                print('done')
            except:
                pass
    'Attaching the attachment'
    if attach is not None:
        try:
            part = MIMEBase('application', 'octet-stream')
            part.set_payload(open(attach, 'rb').read())
            encoders.encode_base64(part)
            part.add_header(
                'Content-Disposition',
                'attachment; filename="%s"' % os.path.basename(attach))
            msg.attach(part)
        except:
            pass
    'For Multiple attachments'
    if attach_multi is not None and len(attach_multi) > 0:
        for attach in attach_multi:
            try:
                part = MIMEBase('application', 'octet-stream')
                part.set_payload(open(attach, 'rb').read())
                encoders.encode_base64(part)
                part.add_header(
                    'Content-Disposition',
                    'attachment; filename="%s"' % os.path.basename(attach))
                msg.attach(part)
            except:
                pass
    '''Entire list of addresses'''
    toaddrs = to_list + cc_list + bcc_list
    try:
        mailServer.sendmail(from_user['user'], toaddrs, msg.as_string())
        print('mail send done-' + from_user['user'])
    except:
        raise
    mailServer.quit()
Пример #25
0
       part = MIMEImage(data, sub_type, encode_quopri)  # should we trust the mime_type ?
     else:
       part = MIMEImage(data, sub_type, encode_base64)
   elif main_type == "text":
     part = MIMEText(data, sub_type, attachment.get("charset", "us-ascii"))
   elif main_type == "audio":
     part = MIMEAudio(data, sub_type, encode_base64)
   elif main_type == "application":
     part = MIMEApplication(data, sub_type, encode_noop)
     if sub_type == "javascript":
       encode_quopri(part)
     else:
       encode_base64(part)
   else:
     part = MIMEBase(main_type, sub_type)
     part.set_payload(data)
     encode_base64(part)
 else:
   part = MIMEBase(main_type, sub_type)
   part.set_payload(data)
   if encoding == "base64":
     encode_base64(part)
   elif encoding == "quoted-printable":
     encode_quopri(part)
   elif encoding == "7or8bit":
     encode_7or8bit(part)
   else:  # elif encoding == "noop":
     encode_noop(part)
 for key, value in attachment.get("replace_header_list", []):
   part.replace_header(key, value)
 for key, value in attachment.get("header_dict", {}).items():  # adds headers, does not replace or set
Пример #26
0
    def send(self, recipients, subject="", body="", filename=None):
        msg = MIMEMultipart()
        if not self._username or not self._userpass:
            raise UserInfoError()

        if isinstance(recipients, str):
            recipients = [recipients]

        msg['From'] = self._username
        msg['To'] = self.COMMASPACE.join(recipients)

        if subject == "":
            msg['Subject'] = self._subject
        else:
            msg['Subject'] = subject

        if body == "":
            body = self._body
        else:
            body = MIMEText(body)

        msg.attach(body)

        if filename is not None:
            import os
            import mimetypes

            file_basename = os.path.basename(filename)
            ctype, encoding = mimetypes.guess_type(filename)

            if ctype is None or encoding is not None:
                ctype = 'application/octet-stream'
            maintype, subtype = ctype.split('/')

            if maintype == 'image':
                from email.mime.image import MIMEImage
                with open(filename, 'rb') as fp:
                    part = MIMEImage(fp.read(), _subtype=subtype)
            else:
                from email.mime.base import MIMEBase
                from email import encoders
                with open(filename, 'rb') as fp:
                    part = MIMEBase(maintype, subtype)
                    part.set_payload(fp.read())
                encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment', filename=file_basename)
            msg.attach(part)

        try:
            self._initialize()
            self._sendmail(recipients, msg)
        except smtplib.SMTPAuthenticationError as e:
            print(str(e))
        except smtplib.SMTPConnectError as e:
            print(str(e))
        except smtplib.SMTPServerDisconnected as e:
            print(str(e))
            self._server = None
            self._initialize()
            self._sendmail(recipients, msg)
        except smtplib.SMTPException as e:
            print(str(e))
        else:
            print("Sent mail from %s to %s, Success!!" % (self._username, recipients))
Пример #27
0
#MIMEImage,只要打开相应图片,再用read()方法读入数据,指明src中的代号是多少,如这里是'Imgid’,在HTML格式里就对应输入。
with open('C:/Users/NJU-GXC/test.png', 'rb') as f:
    mime=MIMEImage(f.read())
    mime.add_header('Content-ID','Imgid')
    message.attach(mime)

with open('C:/Users/NJU-GXC/test.png', 'rb') as f:

    # 设置附件的MIME和文件名,这里是png类型:
    mime = MIMEBase('image', 'png', filename='test.png')
    # 加上必要的头信息:
    mime.add_header('Content-Disposition', 'attachment', filename='test.png')
    mime.add_header('Content-ID', '<0>')
    mime.add_header('X-Attachment-Id', '0')
    # 把附件的内容读进来:
    mime.set_payload(f.read())
    # 用Base64编码:
    encoders.encode_base64(mime)
    # 添加到MIMEMultipart:
    message.attach(mime)
#发送邮件!
try:
    smtpobj=smtplib.SMTP('smtp.163.com', 25)
    smtpobj.set_debuglevel(1)
    smtpobj.login(sender,pwd)
    smtpobj.sendmail(sender,[receiver],message.as_string())
    print('邮件发送成功')
    smtpobj.quit()
except smtplib.SMTPException as e:
    print('邮件发送失败,Case:%s'%e)
	
Пример #28
0
def send_mail(smtp_server, smtp_port, smtp_user, smtp_password, from_address,
              to_addresses, cc_addresses, subject, body_file,
              attachment_files):
    rtn = False
    msgroot = MIMEMultipart('related')
    #    msgroot['Subject'] = Header("%s(%s)"%(subject, datetime.date.today()), 'gbk')
    msgroot['Subject'] = Header("%s" % (subject, ), 'utf8')
    if not from_address:
        from_address = smtp_user
    msgroot['From'] = from_address
    msgroot['To'] = COMMASPACE.join(to_addresses)
    msgroot['Cc'] = COMMASPACE.join(cc_addresses)
    msgroot.preamble = 'This is a multi-part message in MIME format.'
    msgroot.epilogue = ''

    msgAlternative = MIMEMultipart('alternative')
    msgroot.attach(msgAlternative)
    textbody = MIMEText('This is the alternative plain text message.')
    msgAlternative.attach(textbody)

    htmlbody = MIMEText(body_file, 'html', 'utf8')
    msgAlternative.attach(htmlbody)

    for _file_name in attachment_files:
        ftype, fsubtype = 'application', 'octet-stream'
        guesstype, _ = mimetypes.guess_type(_file_name)
        _file_content = open(_file_name).read()
        if guesstype:
            ftype, fsubtype = guesstype.split('/')

        if any(_ext in _file_name
               for _ext in ('.jpg', '.bmp', '.jpeg', '.png', '.gif')):
            info('detect image file (guesstype %s): %s, len(_file_content)=%d',
                 guesstype, _file_name, len(_file_content))
            part = MIMEImage(_file_content, fsubtype)
            part.add_header("Content-ID",
                            "<%s>" % os.path.basename(_file_name))
        else:
            part = MIMEBase(ftype, fsubtype)
            part.set_payload(_file_content, 'utf8')
            part.add_header('Content-Disposition',
                            'inline',
                            filename=os.path.basename(_file_name))
        msgroot.attach(part)

#    _stderr = sys.stderr
#    _f_name = os.path.join('/data/api-log/' if os.path.exists('/data/api-log/') else '/tmp', 'sendmail_dbg-%s.txt' % date.today())
#    _f = open(_f_name, 'a')
#    _f.write('\n\n\n%s %s %s\n\n' % ('-*' * 20, datetime.today(), '-*' * 20))
#    info('smtp debug output to %s', _f_name)
#    smtplib.stderr = _f
#    smtp = smtplib.SMTP()
    smtp = smtplib.SMTP(smtp_server)
    #    smtp.set_debuglevel(1)
    while True:
        info('connecting mail server %s:%d ...', smtp_server, smtp_port)
        try:
            smtp.connect(smtp_server, smtp_port)
            break
        except smtplib.SMTPConnectError:
            info(
                'got SMTPConnectError when trying to connect mail server ! while try after 30 seconds.'
            )
        except Exception as e:
            info('got Error: %s', e)
            return rtn

    try:
        try:
            smtp.starttls()
        except (smtplib.SMTPHeloError, smtplib.SMTPException, RuntimeError):
            pass
        smtp.login(smtp_user, smtp_password)
        info('login ok.')
        to = list(chain(to_addresses, cc_addresses))
        info('send to: %s ...', to)
        smtp.sendmail(msgroot['From'], to, msgroot.as_string())
        info('send ok.')
        rtn = True
    except (smtplib.SMTPAuthenticationError, smtplib.SMTPRecipientsRefused,
            smtplib.SMTPHeloError, smtplib.SMTPSenderRefused,
            smtplib.SMTPDataError) as e:
        info('got %s', e)
    finally:
        smtp.close()


#    _f.close()
#    smtplib.stderr = _stderr
    return rtn
Пример #29
0
def _send_to_mail_exchanger(mail_exchanger,
                            mail_from,
                            rcpt_to,
                            From="",
                            To="",
                            Subject="",
                            Date=None,
                            Body="",
                            attachments=None,
                            encoding="gbk"):

    # 构造MIMEMultipart对象做为根容器
    main_msg = MIMEMultipart()
    # 设置根容器属性
    main_msg['From'] = From
    main_msg['To'] = To
    main_msg['Subject'] = Subject
    if Date:
        main_msg['Date'] = Date
    else:
        main_msg['Date'] = formatdate()

    # 构造MIMEText对象做为邮件显示内容并附加到根容器
    text_msg = MIMEText(Body, 'html', encoding)
    main_msg.attach(text_msg)

    # 构造MIMEBase对象做为文件附件内容并附加到根容器
    if attachments:
        for attachment in attachments:
            if not os.path.isfile(attachment):
                continue
            if IsImage(attachment):
                try:
                    fp = open(attachment, "rb")
                    file_msg = MIMEImage(fp.read())
                    fp.close()
                    file_msg.add_header(
                        "Content-ID",
                        os.path.basename(attachment).replace(".jpg",
                                                             "").replace(
                                                                 ".png", ""))
                    main_msg.attach(file_msg)
                except:
                    pass
            else:
                file_msg = MIMEBase("application", "octet-stream")
                f = open(attachment, 'rb')
                file_msg.set_payload(f.read())
                f.close()
                email.encoders.encode_base64(file_msg)
                file_msg.add_header('Content-Disposition',
                                    'attachment',
                                    filename=os.path.basename(attachment))
                main_msg.attach(file_msg)

    # 用smtp发送邮件
    data = main_msg.as_string()
    for i in range(2):
        try:
            # Log(mail_exchanger)
            server = smtplib.SMTP(mail_exchanger)
            # Log(mail_from)
            # Log(rcpt_to)
            ret = server.sendmail(mail_from, rcpt_to, data)
            break
        except:
            import traceback
            # Log(traceback.format_exc())
            ret = False
            try:
                server.quit()
            except:
                pass
    try:
        server.quit()
    except:
        pass

    if ret == False or ret:
        # print "发往如下的邮件失败:",rcpt_to
        return False
    return True
Пример #30
0
    def send_message(
        self,
        sender: str,
        recipients: str,
        subject: str,
        body: str,
        attachments: str = None,
        html: bool = False,
    ) -> None:
        """Send SMTP email

        Valid sender values:
            - First Lastname <address@domain>
            - address@domain

        :param sender: who is sending, ie. 'from'
        :param recipients: who is receiving, ie. 'to'
        :param subject: mail subject field
        :param body: mail body content
        :param attachments: list of filepaths to attach, defaults to []
        :param html: if message content is in HTML, default `False`
        """
        if self.smtp_conn is None:
            raise ValueError("Requires authorized SMTP connection")
        add_charset("utf-8", QP, QP, "utf-8")
        attachments = attachments or []
        if not isinstance(attachments, list):
            attachments = attachments.split(",")

        msg = MIMEMultipart()

        if len(attachments) > 0:
            for filename in attachments:
                self.logger.debug("Adding attachment: %s", filename)
                with open(filename, "rb") as attachment:
                    _, ext = filename.lower().rsplit(".", 1)
                    ctype, _ = mimetypes.guess_type(filename)
                    _, subtype = ctype.split("/", 1)
                    if ext in IMAGE_FORMATS:
                        # image attachment
                        part = MIMEImage(
                            attachment.read(),
                            name=os.path.basename(filename),
                            _subtype=subtype,
                        )
                    else:
                        # attach other filetypes
                        part = MIMEBase("application", "octet-stream")
                        part.set_payload(attachment.read())
                        encoders.encode_base64(part)
                    part.add_header(
                        "Content-Disposition",
                        f"attachment; filename= {Path(filename).name}",
                    )
                    msg.attach(part)

        msg["From"] = sender
        msg["Subject"] = Header(subject, "utf-8")

        if html:
            htmlpart = MIMEText(body, "html", "UTF-8")
            msg.attach(htmlpart)
        else:
            textpart = MIMEText(body, "plain", "UTF-8")
            msg.attach(textpart)

        # Create a generator and flatten message object to 'file’
        str_io = StringIO()
        g = Generator(str_io, False)
        g.flatten(msg)

        if not isinstance(recipients, list):
            recipients = recipients.split(",")
        try:
            self.smtp_conn.sendmail(sender, recipients, str_io.getvalue())
        except Exception as err:
            raise ValueError(f"Send Message failed: {err}")