コード例 #1
0
    def alert(self, matches):
        body = self.create_alert_body(matches)

        # Add Jira ticket if it exists
        if self.pipeline is not None and 'jira_ticket' in self.pipeline:
            url = '%s/browse/%s' % (self.pipeline['jira_server'],
                                    self.pipeline['jira_ticket'])
            body += '\nJira ticket: %s' % (url)

        to_addr = self.rule['email']
        if 'email_from_field' in self.rule:
            recipient = lookup_es_key(matches[0],
                                      self.rule['email_from_field'])
            if isinstance(recipient, str):
                if '@' in recipient:
                    to_addr = [recipient]
                elif 'email_add_domain' in self.rule:
                    to_addr = [recipient + self.rule['email_add_domain']]
            elif isinstance(recipient, list):
                to_addr = recipient
                if 'email_add_domain' in self.rule:
                    to_addr = [
                        name + self.rule['email_add_domain']
                        for name in to_addr
                    ]
        if self.rule.get('email_format') == 'html':
            # email_msg = MIMEText(body, 'html', _charset='UTF-8') # old way
            email_msg = MIMEMultipart()
            msgText = MIMEText(body, 'html', _charset='UTF-8')
            email_msg.attach(msgText)  # Added, and edited the previous line

            for image_key in self.images_dictionary:
                fp = open(
                    os.path.join(self.assets_dir,
                                 self.images_dictionary[image_key]), 'rb')
                img = MIMEImage(fp.read())
                fp.close()
                img.add_header('Content-ID', '<{}>'.format(image_key))
                email_msg.attach(img)
        else:
            email_msg = MIMEText(body, _charset='UTF-8')
        email_msg['Subject'] = self.create_title(matches)
        email_msg['To'] = ', '.join(to_addr)
        email_msg['From'] = self.from_addr
        email_msg['Reply-To'] = self.rule.get('email_reply_to',
                                              email_msg['To'])
        email_msg['Date'] = formatdate()
        if self.rule.get('cc'):
            email_msg['CC'] = ','.join(self.rule['cc'])
            to_addr = to_addr + self.rule['cc']
        if self.rule.get('bcc'):
            to_addr = to_addr + self.rule['bcc']

        try:
            if self.smtp_ssl:
                if self.smtp_port:
                    self.smtp = SMTP_SSL(self.smtp_host,
                                         self.smtp_port,
                                         keyfile=self.smtp_key_file,
                                         certfile=self.smtp_cert_file)
                else:
                    # default port : 465
                    self.smtp = SMTP_SSL(self.smtp_host,
                                         keyfile=self.smtp_key_file,
                                         certfile=self.smtp_cert_file)
            else:
                if self.smtp_port:
                    self.smtp = SMTP(self.smtp_host, self.smtp_port)
                else:
                    # default port : 25
                    self.smtp = SMTP(self.smtp_host)
                self.smtp.ehlo()
                if self.smtp.has_extn('STARTTLS'):
                    self.smtp.starttls(keyfile=self.smtp_key_file,
                                       certfile=self.smtp_cert_file)
            if 'smtp_auth_file' in self.rule:
                self.smtp.login(self.user, self.password)
        except (SMTPException, error) as e:
            raise EAException("Error connecting to SMTP host: %s" % (e))
        except SMTPAuthenticationError as e:
            raise EAException("SMTP username/password rejected: %s" % (e))
        self.smtp.sendmail(self.from_addr, to_addr, email_msg.as_string())
        self.smtp.quit()

        elastalert_logger.info("Sent email to %s" % (to_addr))
コード例 #2
0
ファイル: sendEmail.py プロジェクト: arvindmk/FlaskApp
def execute(emailAddress, filenameJPG, qrcode, img, autoThrashed, fromMFP):
    timestamp1 = str(dt.timestamp(dt.now()))
    subject = '[New Mail Received][Code:' + qrcode + '] New Postal Mail reception notification'
    if (not autoThrashed):
        body = "Dear Sir/Madam,<br><br> A new postal mail intended to you has been recieved and placed in the reception.<br>Please show the above QR code to reception and collect the mail.<br><br><br><img src='cid:image1" + str(
            timestamp1
        ) + "' width=500 height=200></img><br><br><br>If you want to keep the mail, then reply to this mail ID by adding [Keep] in the subject.<br>If you do not want to keep the mail, then reply to this mail ID by adding [Trash] in the subject.<br> <br> Note: The mail will be kept in the reception for a period of 10 days.<br> <br>Regards,<br>Admin"
    else:
        body = "Dear Sir/Madam,<br><br> A new postal mail intented to you has been autoTrashed based on your preferences.<br><br><br><img src='cid:image1" + str(
            timestamp1
        ) + "' width=500 height=200></img><br><br><br> Regards,<br> Admin"
    sender_email = "*****@*****.**"
    password = "******"
    # Create a multipart message and set headers
    msgRoot = MIMEMultipart('related')
    msgRoot["From"] = sender_email
    #message["To"] = emailAddress
    msgRoot["To"] = emailAddress
    msgRoot["Subject"] = subject

    # Add body to email
    msgAlternative = MIMEMultipart('alternative')
    msgRoot.attach(msgAlternative)
    msgText = MIMEText(body)
    msgAlternative.attach(msgText)
    if (not fromMFP):
        filename = "uploads/" + str(filenameJPG)  # In same directory as script
    else:
        filename = "uploads/imageToSave.png"
    filename1 = "qrcode.jpg"
    # Open PDF file in binary mode

    msgText = MIMEText(
        '<img src="cid:image2' + str(timestamp1) +
        '"width=90 height=90></img><br><br>' + body, 'html')
    msgAlternative.attach(msgText)
    fp = open(filename, 'rb')
    msgImage = MIMEImage(fp.read())
    fp.close()
    msgImage.add_header('Content-ID', '<image1' + str(timestamp1) + '>')
    msgRoot.attach(msgImage)
    #fp = open(filename1, 'rb')
    #msgImage1 = MIMEImage(fp.read())
    #fp.close()
    buf = BytesIO()
    img.save(buf)
    image_stream = buf.getvalue()
    msgImage1 = MIMEImage(image_stream)
    msgImage1.add_header('Content-ID', '<image2' + str(timestamp1) + '>')
    msgRoot.attach(msgImage1)
    text = msgRoot.as_string()

    # Log in to server using secure context and send email
    context = ssl.create_default_context()
    with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
        server.login(sender_email, password)
        server.sendmail(sender_email, [
            emailAddress,
            "*****@*****.**",
        ], text)
    os.remove(filename)
コード例 #3
0
ファイル: send-mail.py プロジェクト: ifeatu/toolbox
 for file in options.attach.split(','):
     file = file.strip()
     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
         part = MIMEText(fp.read(), _subtype=subtype)
         fp.close()
     elif maintype == 'image':
         fp = open(file, 'rb')
         part = MIMEImage(fp.read(), _subtype=subtype)
         fp.close()
     elif maintype == 'audio':
         fp = open(file, 'rb')
         part = MIMEAudio(fp.read(), _subtype=subtype)
         fp.close()
     else:
         fp = open(file, 'rb')
         part = MIMEBase(maintype, subtype)
         part.set_payload(fp.read())
         fp.close()
         # Encode the payload using Base64
         encoders.encode_base64(part)
     # Set the filename parameter
     filename = os.path.basename(file)
     part.add_header('Content-Disposition', 'attachment', filename=filename)
コード例 #4
0
msg = MIMEMultipart()
msg['Subject'] = 'MAIL_SUBJECT'  # SUBJECT
msg['From'] = 'SENDER_EMAIL'
html = """\
<html>
  <head></head>
  <body>
    <p>
    BODY_CONTENT
    </p>
  </body>
</html>
"""
txt = MIMEText(html, 'html')
msg.attach(txt)
image = MIMEImage(img_data, name=os.path.basename('ATTACHMENT_IMAGE'))

msg.attach(image)

server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login('SENDER_EMAIL', 'SENDER_PASSWORD')
email_data = csv.reader(open('DATA_FILE', 'r'))
email_pattern = re.compile("^.+@.+\..+$")
for row in email_data:
    if (email_pattern.search(row[1])):
        del msg['To']
        msg['To'] = row[1]
        try:
            server.sendmail('SENDER_EMAIL', [row[1]], msg.as_string())
        except SMTPException:
コード例 #5
0
ctype, encoding = mimetypes.guess_type(fileToSend)
if ctype is None or encoding is not None:
    ctype = "application/octet-stream"

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


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)

# send it via gmail
コード例 #6
0
    def do(self, action, options=None):
        """
        This method executes the defined action in the given event.

        :param action:
        :param options: Contains the flask parameters g, request, response
            and the handler_def configuration
        :type options: dict
        :return:
        """
        ret = True
        g = options.get("g")
        request = options.get("request")
        response = options.get("response")
        content = self._get_response_content(response)
        handler_def = options.get("handler_def")
        handler_options = handler_def.get("options", {})
        notify_type = handler_options.get("To", NOTIFY_TYPE.TOKENOWNER)
        try:
            logged_in_user = g.logged_in_user
        except Exception:
            logged_in_user = {}

        tokenowner = self._get_tokenowner(request)
        log.debug(u"Executing event for action {0!r}, user {1!r}, "
                  u"logged_in_user {2!r}".format(action, tokenowner,
                                                 logged_in_user))

        # Determine recipient
        recipient = None

        if notify_type == NOTIFY_TYPE.TOKENOWNER and not tokenowner.is_empty():
            recipient = {
                "givenname": tokenowner.info.get("givenname"),
                "surname": tokenowner.info.get("surname"),
                "username": tokenowner.login,
                "userrealm": tokenowner.realm,
                "email": tokenowner.info.get("email"),
                "mobile": tokenowner.info.get("mobile")
            }
        elif notify_type == NOTIFY_TYPE.INTERNAL_ADMIN:
            username = handler_options.get("To " + NOTIFY_TYPE.INTERNAL_ADMIN)
            internal_admin = get_db_admin(username)
            recipient = {
                "givenname": username,
                "email": internal_admin.email if internal_admin else ""
            }
        elif notify_type == NOTIFY_TYPE.ADMIN_REALM:
            # Send emails to all the users in the specified admin realm
            admin_realm = handler_options.get("To " + NOTIFY_TYPE.ADMIN_REALM)
            ulist = get_user_list({"realm": admin_realm})
            # create a list of all user-emails, if the user has an email
            emails = [u.get("email") for u in ulist if u.get("email")]
            recipient = {
                "givenname": "admin of realm {0!s}".format(admin_realm),
                "email": emails
            }
        elif notify_type == NOTIFY_TYPE.LOGGED_IN_USER:
            # Send notification to the logged in user
            if logged_in_user.get(
                    "username") and not logged_in_user.get("realm"):
                # internal admins have no realm
                internal_admin = get_db_admin(logged_in_user.get("username"))
                if internal_admin:
                    recipient = {
                        "givenname": logged_in_user.get("username"),
                        "email": internal_admin.email if internal_admin else ""
                    }
            else:
                # Try to find the user in the specified realm
                user_obj = User(logged_in_user.get("username"),
                                logged_in_user.get("realm"))
                if user_obj:
                    recipient = {
                        "givenname": user_obj.info.get("givenname"),
                        "surname": user_obj.info.get("surname"),
                        "email": user_obj.info.get("email"),
                        "mobile": user_obj.info.get("mobile")
                    }

        elif notify_type == NOTIFY_TYPE.EMAIL:
            email = handler_options.get("To " + NOTIFY_TYPE.EMAIL,
                                        "").split(",")
            recipient = {"email": email}
        else:
            log.warning("Was not able to determine the recipient for the user "
                        "notification: {0!s}".format(handler_def))

        if recipient or action.lower() == "savefile":
            # In case of "savefile" we do not need a recipient
            # Collect all data
            body = handler_options.get("body") or DEFAULT_BODY
            if body.startswith("file:"):  # pragma no cover
                # We read the template from the file.
                filename = body[5:]
                try:
                    with open(filename, "r", encoding="utf-8") as f:
                        body = f.read()
                except Exception as e:
                    log.warning(
                        u"Failed to read email template from file {0!r}: {1!r}"
                        .format(filename, e))
                    log.debug(u"{0!s}".format(traceback.format_exc()))

            subject = handler_options.get("subject") or \
                      "An action was performed on your token."
            serial = request.all_data.get("serial") or \
                     content.get("detail", {}).get("serial") or \
                     g.audit_object.audit_data.get("serial")
            registrationcode = content.get("detail",
                                           {}).get("registrationcode")
            pin = content.get("detail", {}).get("pin")
            googleurl_value = content.get("detail", {}).get("googleurl",
                                                            {}).get("value")
            googleurl_img = content.get("detail", {}).get("googleurl",
                                                          {}).get("img")
            tokentype = None
            if serial:
                tokens = get_tokens(serial=serial)
                if tokens:
                    tokentype = tokens[0].get_tokentype()
            else:
                token_objects = get_tokens(user=tokenowner)
                serial = ','.join([tok.get_serial() for tok in token_objects])

            tags = create_tag_dict(
                logged_in_user=logged_in_user,
                request=request,
                client_ip=g.client_ip,
                pin=pin,
                googleurl_value=googleurl_value,
                recipient=recipient,
                tokenowner=tokenowner,
                serial=serial,
                tokentype=tokentype,
                registrationcode=registrationcode,
                escape_html=action.lower() == "sendmail"
                and handler_options.get("mimetype", "").lower() == "html")

            body = body.format(googleurl_img=googleurl_img, **tags)
            subject = subject.format(**tags)
            # Send notification
            if action.lower() == "sendmail":
                emailconfig = handler_options.get("emailconfig")
                mimetype = handler_options.get("mimetype", "plain")
                useremail = recipient.get("email")
                reply_to = handler_options.get("reply_to")
                attach_qrcode = handler_options.get("attach_qrcode", False)

                if attach_qrcode and googleurl_img:
                    # get the image part of the googleurl
                    googleurl = urlopen(googleurl_img)
                    mail_body = MIMEMultipart('related')
                    mail_body.attach(MIMEText(body, mimetype))
                    mail_img = MIMEImage(googleurl.read())
                    mail_img.add_header('Content-ID', '<token_image>')
                    mail_img.add_header(
                        'Content-Disposition',
                        'inline; filename="{0!s}.png"'.format(serial))
                    mail_body.attach(mail_img)
                    body = mail_body
                try:
                    ret = send_email_identifier(emailconfig,
                                                recipient=useremail,
                                                subject=subject,
                                                body=body,
                                                reply_to=reply_to,
                                                mimetype=mimetype)
                except Exception as exx:
                    log.error("Failed to send email: {0!s}".format(exx))
                    ret = False
                if ret:
                    log.info("Sent a notification email to user {0}".format(
                        recipient))
                else:
                    log.warning("Failed to send a notification email to user "
                                "{0}".format(recipient))

            elif action.lower() == "savefile":
                spooldir = get_app_config_value(
                    "PI_NOTIFICATION_HANDLER_SPOOLDIRECTORY",
                    "/var/lib/privacyidea/notifications/")
                filename = handler_options.get("filename")
                random = get_alphanum_str(16)
                filename = filename.format(random=random,
                                           **tags).lstrip(os.path.sep)
                outfile = os.path.normpath(os.path.join(spooldir, filename))
                if not outfile.startswith(spooldir):
                    log.error(
                        u'Cannot write outside of spooldir {0!s}!'.format(
                            spooldir))
                else:
                    try:
                        with open(outfile, "w") as f:
                            f.write(body)
                    except Exception as err:
                        log.error(
                            u"Failed to write notification file: {0!s}".format(
                                err))

            elif action.lower() == "sendsms":
                smsconfig = handler_options.get("smsconfig")
                userphone = recipient.get("mobile")
                try:
                    ret = send_sms_identifier(smsconfig, userphone, body)
                except Exception as exx:
                    log.error("Failed to send sms: {0!s}".format(exx))
                    ret = False
                if ret:
                    log.info("Sent a notification sms to user {0}".format(
                        recipient))
                else:
                    log.warning("Failed to send a notification email to user "
                                "{0}".format(recipient))

        return ret
コード例 #7
0
ファイル: mailing.py プロジェクト: fcisz2502/afUtility
    def send(self, subject, content, png=[], files=[], cc=[]):
        # 第三方 SMTP 服务
        _mail_host = mail_host  # 设置服务器
        mail_user = senderEmail  # 用户名
        mail_pass = senderEmailPassword  # 口令
        sender = senderEmail

        message = MIMEMultipart('related')
        message['From'] = Header("FCI", 'utf-8')
        message['To'] = Header("fcier", 'utf-8')

        subject = self.machineID + "-" + self.subjectPrefix + ' ' + subject
        message['Subject'] = Header(subject, 'utf-8')

        msgAlter = MIMEMultipart('alternative')
        message.attach(msgAlter)

        # add content to email
        mail_msg = """<p>""" + content + """</p>"""

        # attach id to each image
        for j in range(len(png)):
            mail_msg += """<p><img src="cid:image%s"></p>\n""" % j
        msgAlter.attach(MIMEText(mail_msg, 'html', 'utf-8'))

        # add images to email, images will not displayed if the nex three lines are deleted
        if png:
            for i, p in enumerate(png):
                with open(p, 'rb') as f:
                    msgImage = MIMEImage(f.read())
                msgImage.add_header('Content-ID', '<image' + str(i) + '>')
                message.attach(msgImage)

        if files:
            for i in range(len(files)):
                file = files[i]
                filename = file.split("\\")[-1]
                att1 = MIMEText(open(file, 'rb').read(), 'base64', 'utf-8')
                att1["Content-Type"] = 'application/octet-stream'
                # 这里的filename可以任意写,写什么名字,邮件中显示什么名字
                att1[
                    "Content-Disposition"] = 'attachment; filename="' + filename + '"'
                message.attach(att1)

        try:
            smtpObj = smtplib.SMTP()
            smtpObj.connect(_mail_host, 25)  # 25 为 SMTP 端口号
            smtpObj.login(mail_user, mail_pass)

            if isinstance(cc, list):
                smtpObj.sendmail(sender, self.receivers + cc,
                                 message.as_string())
            else:
                # add alert information, then send email to receivers but cc
                # go to next line, use“\r\n” if is string, or "<br>" if html
                msgAlter.attach(
                    MIMEText(
                        "<br><br>cc Error: please input cc email addr in list, such as: ['xxx@xxx']",
                        'html', 'utf-8'))
                smtpObj.sendmail(sender, self.receivers, message.as_string())

            print("mailing done.")

        except smtplib.SMTPException:
            print("Error: mailing failed!")
コード例 #8
0
ファイル: pgn.py プロジェクト: MichaelB7/picochess
    def _use_smtp(self, subject, body, path):
        # if self.smtp_server is not provided than don't try to send email via smtp service
        logging.debug('SMTP Mail delivery: Started')
        # change to smtp based mail delivery
        # depending on encrypted mail delivery, we need to import the right lib
        if self.smtp_encryption:
            # lib with ssl encryption
            logging.debug('SMTP Mail delivery: Import SSL SMTP Lib')
            from smtplib import SMTP_SSL as SMTP
        else:
            # lib without encryption (SMTP-port 21)
            logging.debug(
                'SMTP Mail delivery: Import standard SMTP Lib (no SSL encryption)'
            )
            from smtplib import SMTP
        conn = False
        try:
            outer = MIMEMultipart()
            outer['Subject'] = subject  # put subject to mail
            outer['From'] = 'Your PicoChess computer <{}>'.format(
                self.smtp_from)
            outer['To'] = self.email
            outer.attach(MIMEText(body, 'plain'))  # pack the pgn to Email body

            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':
                with open(path) as fpath:
                    msg = MIMEText(fpath.read(), _subtype=subtype)
            elif maintype == 'image':
                with open(path, 'rb') as fpath:
                    msg = MIMEImage(fpath.read(), _subtype=subtype)
            elif maintype == 'audio':
                with open(path, 'rb') as fpath:
                    msg = MIMEAudio(fpath.read(), _subtype=subtype)
            else:
                with open(path, 'rb') as fpath:
                    msg = MIMEBase(maintype, subtype)
                    msg.set_payload(fpath.read())
                encoders.encode_base64(msg)
            msg.add_header('Content-Disposition',
                           'attachment',
                           filename=os.path.basename(path))
            outer.attach(msg)

            logging.debug('SMTP Mail delivery: trying to connect to ' +
                          self.smtp_server)
            conn = SMTP(self.smtp_server)  # contact smtp server
            conn.set_debuglevel(False)  # no debug info from smtp lib
            if self.smtp_user is not None and self.smtp_pass is not None:
                logging.debug(
                    'SMTP Mail delivery: trying to log to SMTP Server')
                conn.login(self.smtp_user,
                           self.smtp_pass)  # login at smtp server

            logging.debug('SMTP Mail delivery: trying to send email')
            conn.sendmail(self.smtp_from, self.email, outer.as_string())
            logging.debug(
                'SMTP Mail delivery: successfuly delivered message to SMTP server'
            )
        except Exception as smtp_exc:
            logging.error('SMTP Mail delivery: Failed')
            logging.error('SMTP Mail delivery: ' + str(smtp_exc))
        finally:
            if conn:
                conn.close()
            logging.debug('SMTP Mail delivery: Ended')
コード例 #9
0
def send_email_smtp(  # pylint: disable=invalid-name,too-many-arguments,too-many-locals
    to: str,
    subject: str,
    html_content: str,
    config: Dict[str, Any],
    files: Optional[List[str]] = None,
    data: Optional[Dict[str, str]] = None,
    images: Optional[Dict[str, bytes]] = None,
    dryrun: bool = False,
    cc: Optional[str] = None,
    bcc: Optional[str] = None,
    mime_subtype: str = "mixed",
) -> None:
    """
    Send an email with html content, eg:
    send_email_smtp(
        '*****@*****.**', 'foo', '<b>Foo</b> bar',['/dev/null'], dryrun=True)
    """
    smtp_mail_from = config["SMTP_MAIL_FROM"]
    smtp_mail_to = get_email_address_list(to)

    msg = MIMEMultipart(mime_subtype)
    msg["Subject"] = subject
    msg["From"] = smtp_mail_from
    msg["To"] = ", ".join(smtp_mail_to)
    msg.preamble = "This is a multi-part message in MIME format."

    recipients = smtp_mail_to
    if cc:
        smtp_mail_cc = get_email_address_list(cc)
        msg["CC"] = ", ".join(smtp_mail_cc)
        recipients = recipients + smtp_mail_cc

    if bcc:
        # don't add bcc in header
        smtp_mail_bcc = get_email_address_list(bcc)
        recipients = recipients + smtp_mail_bcc

    msg["Date"] = formatdate(localtime=True)
    mime_text = MIMEText(html_content, "html")
    msg.attach(mime_text)

    # Attach files by reading them from disk
    for fname in files or []:
        basename = os.path.basename(fname)
        with open(fname, "rb") as f:
            msg.attach(
                MIMEApplication(
                    f.read(),
                    Content_Disposition="attachment; filename='%s'" % basename,
                    Name=basename,
                )
            )

    # Attach any files passed directly
    for name, body in (data or {}).items():
        msg.attach(
            MIMEApplication(
                body, Content_Disposition="attachment; filename='%s'" % name, Name=name
            )
        )

    # Attach any inline images, which may be required for display in
    # HTML content (inline)
    for msgid, imgdata in (images or {}).items():
        image = MIMEImage(imgdata)
        image.add_header("Content-ID", "<%s>" % msgid)
        image.add_header("Content-Disposition", "inline")
        msg.attach(image)

    send_mime_email(smtp_mail_from, recipients, msg, config, dryrun=dryrun)
コード例 #10
0
def sendEmail(sender,
              recipients,
              subject,
              body,
              attachments=None,
              cc=None,
              bcc=None,
              contentType='text/html',
              server=None,
              useMSExchange=None,
              encoding='utf-8'):
    """
    Sends an email from the inputted email address to the
    list of given recipients with the inputted subject and
    body.  This will also attach the inputted list of
    attachments to the email.  The server value will default 
    to mail.<sender_domain> and you can use a ':' to specify 
    a port for the server.
    
    :param      sender          <str>
    :param      recipients      <list> [ <str>, .. ]
    :param      subject         <str>
    :param      body            <str>
    :param      attachments     <list> [ <str>, .. ]
    :param      cc              <list> [ <str>, .. ]
    :param      bcc             <list> [ <str>, .. ]
    :param      contentType     <str>
    :param      server          <str>
    
    :return     <bool> success
    """
    if attachments is None:
        attachments = []
    if cc is None:
        cc = []
    if bcc is None:
        bcc = []

    if server is None:
        server = NOTIFY_SERVER
    if useMSExchange is None:
        useMSExchange = NOTIFY_SERVER_MSX

    # normalize the data
    sender = nstr(sender)
    recipients = map(nstr, recipients)

    # make sure we have valid information
    if not isEmail(sender):
        err = errors.NotifyError('%s is not a valid email address' % sender)
        logger.error(err)
        return False

    # make sure there are recipients
    if not recipients:
        err = errors.NotifyError('No recipients were supplied.')
        logger.error(err)
        return False

    # build the server domain
    if not server:
        err = errors.NotifyError('No email server specified')
        logger.error(err)
        return False

    # create the email
    msg = MIMEMultipart(_subtype='related')
    msg['Subject'] = projex.text.toUtf8(subject)
    msg['From'] = sender
    msg['To'] = ','.join(recipients)
    msg['Cc'] = ','.join([nstr(addr) for addr in cc if isEmail(addr)])
    msg['Bcc'] = ','.join([nstr(addr) for addr in bcc if isEmail(addr)])
    msg['Date'] = nstr(datetime.datetime.now())
    msg['Content-type'] = 'Multipart/mixed'

    msg.preamble = 'This is a multi-part message in MIME format.'
    msg.epilogue = ''

    # build the body
    bodyhtml = projex.text.toUtf8(body)
    eattach = []

    # include inline images
    filepaths = re.findall('<img\s+src="(file:///[^"]+)"[^/>]*/?>', bodyhtml)
    for filepath in filepaths:
        filename = filepath.replace('file:///', '')
        if os.path.exists(filename) and filename not in attachments:
            # replace with the attachment id
            cid = 'cid:%s' % os.path.basename(filename)
            bodyhtml = bodyhtml.replace(filename, cid)

            # add the image to the attachments
            fp = open(nstr(filename), 'rb')
            msgImage = MIMEImage(fp.read())
            fp.close()

            # add the msg image to the msg
            content_id = '<%s>' % os.path.basename(filename)
            inline_link = 'inline; filename="%s"' % os.path.basename(filename)
            msgImage.add_header('Content-ID', content_id)
            msgImage.add_header('Content-Disposition', inline_link)

            eattach.append(msgImage)
            attachments.append(filename)

    # create the body text
    msgText = MIMEText(bodyhtml, contentType, encoding)
    msgText['Content-type'] = contentType

    # include attachments
    for attach in attachments:
        fp = open(nstr(attach), 'rb')
        txt = MIMEBase('application', 'octet-stream')
        txt.set_payload(fp.read())
        fp.close()

        encode_base64(txt)
        attachment = 'attachment; filename="%s"' % os.path.basename(attach)
        txt.add_header('Content-Disposition', attachment)
        eattach.append(txt)

    eattach.insert(0, msgText)

    # add the attachments to the message
    for attach in eattach:
        msg.attach(attach)

    # create the connection to the email server
    try:
        smtp_server = smtplib.SMTP(nstr(server))
    except socket.gaierror, err:
        logger.error(err)
        return False
コード例 #11
0
ファイル: sendmail-attachment.py プロジェクト: zeus911/py-op
def addimg(src, imgid):
    fp = open(src, 'rb')
    msgImage = MIMEImage(fp.read())
    fp.close()
    msgImage.add_header('Content-ID', imgid)
    return msgImage
コード例 #12
0
ファイル: sendhtml.py プロジェクト: gjc159357/python3
attfile = 'test.py'
basename = os.path.basename(attfile)
fp = open(attfile, 'rb')
att = email.mime.text.MIMEText(fp.read(), 'html', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att.add_header(
    'Content-Disposition', 'attachment',
    filename=('utf-8', '',
              basename))  #three-tuple of (charset, language, value),
# encoders.encode_base64(att)
msg.attach(att)
##########

#################
img = "1.jpg"
fimg = open(img, "rb")
imgattr = MIMEImage(fimg.read())
fimg.close()
imgattr.add_header('Content-ID', '<image1>')
msg.attach(imgattr)
################

smtp = smtplib.SMTP()
smtp.connect('smtp.163.com', '25')
smtp.login('*****@*****.**', 'LingJing2315')
smtp.sendmail(
    from_addr='*****@*****.**',
    to_addrs=['*****@*****.**', '*****@*****.**', '*****@*****.**'],
    msg=msg.as_string())
smtp.quit()
コード例 #13
0
def send_files_via_email(conf, dir, filenames) -> str:
    """
    Send a list of files to a pre-configured address
    :param conf: ConfigReader
    :param dir: input directory
    :param filenames: files to be attachte to the mail
    :return: success message: 'OK' or error message
    """

    # Create the enclosing (outer) message
    outer = MIMEMultipart()
    outer['Subject'] = conf.TITLE
    outer['To'] = conf.RECIPIENT
    outer['From'] = conf.FROM
    outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'

    for file in filenames:
        filename = os.path.join(dir, file)
        if not os.path.isfile(filename):
            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(filename)
        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(filename) as fp:
                # Note: we should handle calculating the charset
                msg = MIMEText(fp.read(), _subtype=subtype)
        elif maintype == 'image':
            with open(filename, 'rb') as fp:
                msg = MIMEImage(fp.read(), _subtype=subtype)
        else:
            with open(filename, '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=filename)
        outer.attach(msg)
    # Now send the message
    composed = outer.as_string()
    logging.info("connecting to smtp://%s:%s" %  (conf.SMTP_SMART_HOST, conf.SMTP_PORT))
    if conf.USE_TLS:
        ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
        ssl_context.options |= ssl.OP_NO_SSLv2
        # ssl_context.options |= ssl.OP_NO_SSLv3  # TODO: fix " tlsv1 alert decode error"
        # Taken from http://stackoverflow.com/questions/33857698/sending-email-from-python-using-starttls
        ssl_context.set_ciphers(
            'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'
            'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'
            '!eNULL:!MD5')
        ssl_context.set_default_verify_paths()
        ssl_context.verify_mode = ssl.CERT_REQUIRED
        try:
            smtp_server = smtplib.SMTP_SSL(local_hostname='PVZDlivdCD', context=ssl_context)
            #


            # smtp_server.set_debuglevel(1)
            smtp_server.connect (host=conf.SMTP_SMART_HOST, port=conf.SMTP_PORT)
        except Exception as e:
            errmsg = "Connection to mail server smtp://%s:%s failed: %s" %  (conf.SMTP_SMART_HOST, conf.SMTP_PORT, str(e))
            logging.error(errmsg)
            return errmsg
        # only TLSv1 or higher
        logging.info("sending EHLO")
        smtp_server.ehlo()
        try:
            logging.info("authenticating to SMTP server")
            smtp_server.login(conf.ACCOUNT, conf.PASSWORD)
        except Exception as e:
            logging.error("Authentication to mail server failed: " + str(e))
            smtp_server.quit()
            return "Authentication to mail server failed: " + str(e)
    else:
        try:
            smtp_server = smtplib.SMTP(local_hostname='PVZDliveCD')
            smtp_server.set_debuglevel(1)
            smtp_server.connect (host=conf.SMTP_SMART_HOST, port=conf.SMTP_PORT)
        except Exception as e:
            errmsg = "Connection to mail server smtp://%s:%s failed: %s" %  (conf.SMTP_SMART_HOST, conf.SMTP_PORT, str(e))
            logging.error(errmsg)
            return errmsg
    try:
        logging.info("sending message")
        smtp_server.sendmail(conf.FROM, conf.RECIPIENT, composed)
    except Exception as e:
        logging.error('Sending message failed: ' + str(e))
        smtp_server.quit()
        return 'Sending message failed: ' + str(e)
    smtp_server.quit()
    return "OK"
コード例 #14
0
def sendMail(content):
    #send message to everyone in Database

    fromaddr = "*****@*****.**"
    toaddr = "*****@*****.**"
    x = 0

    # Define these once; use them twice!

    # Create the root message and fill in the from, to, and subject headers
    msgRoot = MIMEMultipart('related')
    msgRoot['Subject'] = 'Contest Reminder'
    msgRoot['From'] = fromaddr
    msgRoot['To'] = toaddr
    msgRoot.preamble = 'This is a multi-part message in MIME format.'

    # Encapsulate the plain and HTML versions of the message body in an
    # 'alternative' part, so message agents can decide which they want to display.
    msgAlternative = MIMEMultipart('alternative')
    msgRoot.attach(msgAlternative)

    msgText = MIMEText('Hello coders! Are you all set for upcoming contest?')
    msgAlternative.attach(msgText)

    # Reading HTML file for styling
    body = ""
    with open('mail.html', 'r', encoding="utf8") as file:
        body = file.read()

    body += '<h1 style="top: 0px; font-size:30px">' + content['Name'] + '</h1>'
    body += '<p style="font-size:17px"><span style="color:green;"> Date 📅: </span>' + content[
        'StartDate'] + '</p>'
    body += '<p style="font-size:17px"><span style="color:green;"> Time ⏰: </span>' + content[
        'StartTime'] + '</p>'
    body += '<p style="font-size:17px"><span style="color:green;"> Duration ⌛️: </span>' + content[
        'Duration'] + '</p>'
    body += '<a class="btn1" href="' + content[
        'contestLink'] + '" style="text-decoration:none">Contest Link</a>'
    if (content['Host'] == 'CODEFORCES'):
        body += '<a class="btn1" href="' + content[
            'regLink'] + '" style="text-decoration:none">Registration Link</a>'

    body2 = ""
    with open('mail2.html', 'r', encoding="utf8") as file:
        body2 = file.read()

    body += body2

    # We reference the image in the IMG SRC attribute by the ID we give it below
    msgText = MIMEText(body, 'html')
    msgAlternative.attach(msgText)

    # This example assumes the image is in the current directory
    hostlogopath = "pic/"
    if (content['Host'] == "CODEFORCES"):
        hostlogopath += 'codeforces.png'
    elif (content['Host'] == "CODECHEF"):
        hostlogopath += 'codechef.png'
    elif (content['Host'] == "HACKEREARTH"):
        hostlogopath += 'hackerearth.png'
    elif (content['Host'] == "HACKERRANK"):
        hostlogopath += 'hackerrank.png'
    elif (content['Host'] == "SPOJ"):
        hostlogopath += 'spoj.jfif'

    fp = open(hostlogopath, 'rb')
    msgImage = MIMEImage(fp.read())
    fp.close()

    # Define the image's ID as referenced above
    msgImage.add_header('Content-ID', '<image1>')
    msgRoot.attach(msgImage)

    # Send the email (this example assumes SMTP authentication is required)
    # creates SMTP session
    s = smtplib.SMTP('smtp.gmail.com', 587)

    # start TLS for security
    s.starttls()

    # Authentication
    s.login(fromaddr, "Harikrushna123")

    # Converts the Multipart msg into a string
    text = msgRoot.as_string()

    # sending the mail
    s.sendmail(fromaddr, toaddr, text)
    x += 1
    # terminating the session
    s.quit()
    print(x)
コード例 #15
0
recipientAddr = "*****@*****.**"   #받는 사람 email 주소.

#create MMIMEBase 
msg = MIMEBase("multipart", "mixed")

msg['Subject'] = "Test email in Python 3.0"
msg['From'] = senderAddr
msg['To'] = recipientAddr

#Make MIMEType
htmlFD = open(htmlFileName, 'rb')
HtmlPart = MIMEText(htmlFD.read(), _charset = 'UTF-8' )
htmlFD.close()

imageFD = open(imageFileName, 'rb')
ImagePart = MIMEImage(imageFD.read())
imageFD.close()

# 만들었던 mime을 MIMEBase에 첨부 시킨다.
msg.attach(ImagePart)
msg.attach(HtmlPart)

#헤더에 첨부 파일에 대한 정보를 추가 시킨다.
msg.add_header('Content-Disposition','attachment',filename=imageFileName)

msg['Subject'] = "test python email"
msg['From'] = senderAddr
msg['To'] = recipientAddr


#메일을 발송한다.
コード例 #16
0
msg = MIMEMultipart('alternative')
msg['From'] = _format_addr('我是Python爱好者 <%s>' % from_addr)
msg['To'] = _format_addr('我是管理员 <%s>' % to_addr)
msg['Subject'] = Header('我来自SMTP的问候……', 'utf-8').encode()

# 邮件正文是MIMEText:
msg.attach(MIMEText('hello, send by Python...', 'plain', 'utf-8'))
msg.attach(
    MIMEText(
        '<html><body><h1>Hello</h1>' + '<p><img src="cid:0"></p>' +
        '</body></html>', 'html', 'utf-8'))

# 添加附件就是加上一个MIMEBase,从本地读取一个图片:
with open('../res/yan.jpg', 'rb') as f:
    # 设置附件的MIME和文件名,这里是png类型:
    mime = MIMEImage(f.read())
    # 加上必要的头信息:
    mime.add_header('Content-ID', '<0>')
    # 把附件的内容读进来:
    # 添加到MIMEMultipart:
    msg.attach(mime)

msg['From'] = _format_addr('Python爱好者 <%s>' % from_addr)
# print('管理员 <%s>' % to_addr)
# msg['To'] = _format_addr('管理员 <%s>' % to_addr)
msg['To'] = formataddr((Header('Python爱好者', 'utf-8').encode(), to_addr))
msg['Subject'] = Header('来自SMTP的问候……', 'utf-8').encode()
print(type(msg['From']), type(msg['To']), type(msg['Subject']))

print('From:', msg['From'])
print('To:', msg['To'])
コード例 #17
0
# this mime is not really a part of python this has another sub package
# called multipart, that exposes a class called MIMEMultipart.
# with this we can send email as plain text or html format

from email.mime.text import MIMEText  # for text
import smtplib  # smtp server import kora holo
from email.mime.image import MIMEImage  # for sending image... ... ..
from pathlib import Path

message = MIMEMultipart()  # here we have created a MIMEMultipart object
message["from"] = "Rafsan"
message["to"] = "*****@*****.**"
message[
    "subject"] = "This is a Test"  # these 3 headers are supported by MIMEMultipart() object.
# but we don't have a header called body. so we need to attach this.

message.attach(MIMEText("Here is the message body"))
message.attach(MIMEImage(Path("rafsan.jpeg").read_bytes(
)))  # here we nned to pass our image data in binary ba byte code akare

with smtplib.SMTP(host="smtp.gmail.com", port=587) as smtp:
    smtp.ehlo(
    )  # with this we are telling the smtp server that, I ama client, iwant to send an email.
    smtp.starttls(
    )  # this will put smtp connection in tls mode. with this all the command we will send to the smtp server, will be encrypted.
    smtp.login(
        "here is the email", "here is the password"
    )  # This is for login the gmail, from which we want to send email.
    smtp.send_message(message)  # pass our email message object
    print("sent")
コード例 #18
0
    def message(self):
        from ..utils import get_attachment_filename_from_url, replace_cid_and_change_headers

        to = anyjson.loads(self.to)
        cc = anyjson.loads(self.cc)
        bcc = anyjson.loads(self.bcc)

        if self.send_from.from_name:
            # Add account name to From header if one is available
            from_email = '"%s" <%s>' % (Header(
                u'%s' % self.send_from.from_name,
                'utf-8'), self.send_from.email_address)
        else:
            # Otherwise only add the email address
            from_email = self.send_from.email_address

        html, text, inline_headers = replace_cid_and_change_headers(
            self.body, self.original_message_id)

        email_message = SafeMIMEMultipart('related')
        email_message['Subject'] = self.subject
        email_message['From'] = from_email

        if to:
            email_message['To'] = ','.join(list(to))
        if cc:
            email_message['cc'] = ','.join(list(cc))
        if bcc:
            email_message['bcc'] = ','.join(list(bcc))

        email_message_alternative = SafeMIMEMultipart('alternative')
        email_message.attach(email_message_alternative)

        email_message_text = SafeMIMEText(text, 'plain', 'utf-8')
        email_message_alternative.attach(email_message_text)

        email_message_html = SafeMIMEText(html, 'html', 'utf-8')
        email_message_alternative.attach(email_message_html)

        for attachment in self.attachments.all():
            if attachment.inline:
                continue

            try:
                storage_file = default_storage._open(
                    attachment.attachment.name)
            except IOError:
                logger.exception('Couldn\'t get attachment, not sending %s' %
                                 self.id)
                return False

            filename = get_attachment_filename_from_url(
                attachment.attachment.name)

            storage_file.open()
            content = storage_file.read()
            storage_file.close()

            content_type, encoding = mimetypes.guess_type(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 == 'text':
                msg = MIMEText(content, _subtype=sub_type)
            elif main_type == 'image':
                msg = MIMEImage(content, _subtype=sub_type)
            elif main_type == 'audio':
                msg = MIMEAudio(content, _subtype=sub_type)
            else:
                msg = MIMEBase(main_type, sub_type)
                msg.set_payload(content)
                Encoders.encode_base64(msg)

            msg.add_header('Content-Disposition',
                           'attachment',
                           filename=os.path.basename(filename))

            email_message.attach(msg)

        # Add the inline attachments to email message header
        for inline_header in inline_headers:
            main_type, sub_type = inline_header['content-type'].split('/', 1)
            if main_type == 'image':
                msg = MIMEImage(inline_header['content'],
                                _subtype=sub_type,
                                name=os.path.basename(
                                    inline_header['content-filename']))
                msg.add_header('Content-Disposition',
                               inline_header['content-disposition'],
                               filename=os.path.basename(
                                   inline_header['content-filename']))
                msg.add_header('Content-ID', inline_header['content-id'])

                email_message.attach(msg)

        return email_message
コード例 #19
0
ファイル: __init__.py プロジェクト: Arpitgoyalgg/ezgmail
def _createMessageWithAttachments(sender,
                                  recipient,
                                  subject,
                                  body,
                                  attachments,
                                  cc=None,
                                  bcc=None,
                                  mimeSubtype="plain",
                                  _threadId=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.

    Note that the ``sender`` argument seems to be ignored by Gmail, which uses the account's actual email address.
    """
    if not isinstance(mimeSubtype, str):
        raise EZGmailTypeError(
            'wrong type passed for mimeSubtype arg; must be "plain" or "html"')
    mimeSubtype = mimeSubtype.lower()
    if mimeSubtype not in ("html", "plain"):
        raise EZGmailValueError(
            'wrong string passed for mimeSubtype arg; mimeSubtype arg must be "plain" or "html"'
        )

    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, mimeSubtype)
    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)

    rawMessage = {
        "raw": base64.urlsafe_b64encode(message.as_bytes()).decode("ascii")
    }
    if _threadId is not None:
        rawMessage['threadId'] = _threadId
    return rawMessage
コード例 #20
0
 def __create_image_data(self, image):
     image_data = MIMEImage(open(image, 'rb').read(), 'jpg')
     image_data.add_header('Content-Disposition',
                           'attachment; filename="image.jpg"')
     return image_data
コード例 #21
0
    alternative_message.attach(text_part)
with open(args.html, "r") as f:
    html_part = MIMEText(f.read(), 'html')
    alternative_message.attach(html_part)

if args.related:
    # We create a related message
    from email.mime.image import MIMEImage
    related_message = MIMEMultipart('related')
    # attach the alternative message to the related one
    related_message.attach(alternative_message)
    # attach the document to the related message
    for pathname in args.related:
        try:
            with open(pathname, "rb") as f:
                image = MIMEImage(f.read())
                # link the image with <img src="cid:logo"/>
                filename = os.path.basename(pathname)
                image.add_header('Content-ID', f"<{filename}>")
        except IOError:
            print(f"{pathname} not found.", file=sys.stderr)
            sys.exit(1)
        related_message.attach(image)
    # attach the related message to the multipart message
    multipart_message.attach(related_message)
else:
    # there's no related message, attach the alternative message
    # to the multipart message
    multipart_message.attach(alternative_message)

if args.attachment:
コード例 #22
0
server.login(os.getenv('EMAIL'), os.getenv('PASSWORD'))

mail = MIMEMultipart()

mail['From'] = "Python Hub"
mail['To'] = os.getenv('TO')
mail['Subject'] = 'A gift from Python Hub'

mail.attach(
    MIMEText("This is an image and audio attachment from Python Hub", 'plain'))

image = open('image.jpg', 'rb')
audio = open('sample.mp3', 'rb')

imageAttachment = MIMEImage(image.read())
imageAttachment.add_header('Content-Disposition',
                           'attachment; filename=image.jpg')
mail.attach(imageAttachment)
image.close()

audioAttachment = MIMEAudio(audio.read(), 'mp3')
audioAttachment.add_header('Content-Disposition',
                           'attachment; filename=sample.mp3')
mail.attach(audioAttachment)
audio.close()

message = mail.as_string()

server.sendmail(os.getenv('EMAIL'), os.getenv('TO'), message)
コード例 #23
0
ファイル: sendmail.py プロジェクト: jimlinntu/gbc-paste
    def create_message_mime(self, name, greeting_image_path, dest_email,
                            gathering_path, gathering_name):
        gmail_user = "******"

        title = name
        greeting_path = Path(greeting_image_path)
        assert (greeting_path.exists())
        gathering = Path(gathering_path)

        msg = MIMEMultipart('related')
        msg['Subject'] = '懷恩堂生命助道會歡迎你!'
        msg['From'] = gmail_user
        msg['To'] = dest_email
        msg.preamble = 'This is a multi-part message in MIME format.'

        msgAlternative = MIMEMultipart('alternative')
        msg.attach(msgAlternative)

        with open("plain.txt", "r", encoding="utf-8") as f:
            plain_content = name + f.read()
            plain_content = re.sub("name_placeholder", name, plain_content)
            plain_content = re.sub("gathering1_placeholder", gathering_name,
                                   plain_content)
            msgText = MIMEText(plain_content)
        msgAlternative.attach(msgText)

        # https://gist.github.com/jossef/2a4a46a899820d5d57b4

        with open("content.txt", "r", encoding="utf-8") as f:
            content = "<div dir=\"ltr\">" + name + f.read().strip() + "</div>"
            # dynamically decide the gathering image's width and height
            width, height = self.get_image_size(gathering)
            content = re.sub("!gathering_width", str(width), content)
            content = re.sub("!gathering_height", str(height), content)
            msgText = MIMEText(content, 'html', "utf-8")

        msgAlternative.attach(msgText)

        title_png = title + ".png"
        with greeting_path.open("rb") as f:
            msgImage = MIMEImage(f.read(), name=title_png)
        # https://stackoverflow.com/questions/37019708/how-can-i-customize-file-name-in-python-mimeimage
        # https://docs.python.org/3.6/library/email.message.html#email.message.EmailMessage.add_header
        msgImage.add_header('Content-Disposition',
                            "attachment",
                            filename=title_png)
        msgImage.add_header('Content-ID', '<greeting>')
        msg.attach(msgImage)

        with gathering.open("rb") as f:
            msgImage = MIMEImage(f.read(), name=gathering_name)
        msgImage.add_header('Content-Disposition',
                            "attachment",
                            filename=gathering_name)
        msgImage.add_header('Content-ID', '<gathering1>')
        msg.attach(msgImage)

        # https://stackoverflow.com/questions/37019708/how-can-i-customize-file-name-in-python-mimeimage

        Path('outgoing.msg').write_bytes(bytes(msg))
        return msg
コード例 #24
0
ファイル: app.py プロジェクト: srinivasgpc/Code-fix
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from pathlib import Path
import smtplib

#mime stands for multy

message = MIMEMultipart()

message["from"] = " KSK vivek"
message["to"] = "*****@*****.**"
message["subject"] = "Auto genarate email with python"

message.attach(MIMEText("Email recieved from vivek"))
message.attach(MIMEImage(Path("vivek.jpg").read_bytes()))

with smtplib.SMTP(host="smtp.gmail.com", port=587) as smtp:
    smtp.ehlo()
    smtp.starttls()
    smtp.login("*****@*****.**", "v8008577345")
    smtp.send_message(message)
    print("sent..")
コード例 #25
0
ファイル: scan.py プロジェクト: csteacherd22/hplip
                msg.preamble = 'Scanned using hp-scan'

                if email_note:
                    txt = MIMEText(email_note)
                    msg.attach(txt)

                if file_saved:
                    txt = MIMEText("attached: %s: %dx%d %s PNG image." %
                        (os.path.basename(output), pixels_per_line, lines, scan_mode))
                else:
                    txt = MIMEText("attached: %dx%d %s PNG image." % (pixels_per_line, lines, scan_mode))

                msg.attach(txt)

                fp = open(output, 'r')
                img = MIMEImage(fp.read())
                fp.close()

                if file_saved:
                    img.add_header('Content-Disposition', 'attachment', filename=os.path.basename(output))

                msg.attach(img)

                sendmail = utils.which("sendmail")

                if sendmail:
                    sendmail = os.path.join(sendmail, 'sendmail')
                    cmd = [sendmail,'-t','-r',email_from]

                    log.debug(repr(cmd))
                    err = None
コード例 #26
0
ファイル: inlinemail.py プロジェクト: mikemu1/Python
img = dict(title=u'Picture report…', path=u'Colors.png', cid=str(uuid.uuid4()))

msg = MIMEMultipart('related')
msg['Subject'] = Header(subj, 'utf-8')
msg['From'] = username
msg['To'] = mail_to
msg_alternative = MIMEMultipart('alternative')
msg.attach(msg_alternative)

msg_text = MIMEText(u'\n\nnow is the time', 'plain', 'utf-8')
# msg_text = MIMEText(u'Who knows'.format(**img), 'plain', 'utf-8')
msg_alternative.attach(msg_text)
'''
msg_html = MIMEText(u'<div dir="ltr">'
                    '<img src="cid:{cid}" alt="{alt}"><br></div>'
                    .format(alt=cgi.escape(img['title'], quote=True), **img),
                    'html', 'utf-8')
msg_alternative.attach(msg_html)
'''
with open(img['path'], 'rb') as file:
    msg_image = MIMEImage(file.read(), name=os.path.basename(img['path']))
    msg.attach(msg_image)
msg_image.add_header('Content-ID', '<{}>'.format(img['cid']))

smtp = smtplib.SMTP(host='smtp.frontier.com', port=587)
print(smtp.ehlo())
# print(smtp.starttls())
print(smtp.login(username, password))
print(smtp.sendmail(username, mail_to, msg.as_string()))
smtp.close()
コード例 #27
0
from mail_account import *

msgRoot = MIMEMultipart('related')
msgRoot['From'] = Header('Rookie Tutorial', 'utf-8')
msgRoot['To'] = Header('stone', 'UTF-8')
msgRoot['Subject'] = Header('Image mail test', 'utf-8')

msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)

mail_msg = """
<p>Python HTML image mail test</p>
<p><a href="http://www.taobao.com">Click me</a></p>
<p>Image presentation:</p>
<p><img src="cid:image1"></p>
"""
msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8'))


fp = open('python.png', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()

msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)

try:
    MailAccount.debug_mail_with_message(msgRoot.as_string())
except Exception, anError:
    print '\nPost failed:', anError
コード例 #28
0
    def __init__(self, fromaddr, toaddr, subject, bodyplain=None,
                 bodyhtml=None, attachments=[]):

        super(Message, self).__init__()
        self['Subject'] = subject
        self['From'] = fromaddr
        if isinstance(toaddr, str):
            toaddr = [toaddr]
        self['To'] = COMMASPACE.join(toaddr)
        self.preamble = 'This is a multi-part message in MIME format.'

        attachment_types = {}
        for att in attachments:
            ctype, encoding = mimetypes.guess_type(att)
            if ctype is None:
                raise RuntimeError("Could not guess the MIME type")
            maintype, subtype = ctype.split('/', 1)
            attachment_types[att] = MType(ctype, encoding, maintype, subtype)

        if bodyplain:
            text = MIMEText(bodyplain, _subtype='plain', _charset='UTF-8')

        if bodyhtml:
            image_cid = {}
            idx = 0
            for aname, atypes in attachment_types.items():
                if atypes.maintype != 'image': continue
                cid = "image{}".format(idx)
                idx += 1
                pattern = 'src\s*=\s*"{}"'.format(aname)
                substitute = 'src="cid:{}"'.format(cid)
                bodyhtml = re.sub(pattern, substitute, bodyhtml,
                                  re.IGNORECASE|re.MULTILINE)
                image_cid[aname] = cid
            html = MIMEText(bodyhtml, _subtype='html', _charset='UTF-8')

        if bodyplain and bodyhtml:
            alternative = MIMEMultipart('alternative')
            alternative.attach(text)
            alternative.attach(html)
            self.attach(alternative)
        elif bodyplain:
            self.attach(text)
        elif bodyhtml:
            self.attach(html)
        else:
            raise RuntimeError("plain text or html message must be present")

        for atname,attype in attachment_types.items():
            if attype.maintype == 'image':
                with open(atname, 'rb') as atfile:
                    atm = MIMEImage(atfile.read(), _subtype=attype.subtype)
                    if atname in image_cid:
                        cid = image_cid[atname]
                        atm.add_header('Content-ID', '<{}>'.format(cid))
            elif attype.maintype == 'text':
                with open(att) as atfile:
                    atm = MIMEText(atfile.read(), _subtype=attype.subtype)
            else:
                raise NotImplementedError(
                    "{} attachments are not implemented".format(attype.ctype))
            atm.add_header('Content-Disposition', 'attachment',
                           filename=atname)
            self.attach(atm)
コード例 #29
0
def send_email_smtp(to,
                    subject,
                    html_content,
                    config,
                    files=None,
                    data=None,
                    images=None,
                    dryrun=False,
                    cc=None,
                    bcc=None,
                    mime_subtype='mixed'):
    """
    Send an email with html content, eg:
    send_email_smtp(
        '*****@*****.**', 'foo', '<b>Foo</b> bar',['/dev/null'], dryrun=True)
    """
    smtp_mail_from = config.get('SMTP_MAIL_FROM')
    to = get_email_address_list(to)

    msg = MIMEMultipart(mime_subtype)
    msg['Subject'] = subject
    msg['From'] = smtp_mail_from
    msg['To'] = ', '.join(to)
    msg.preamble = 'This is a multi-part message in MIME format.'

    recipients = to
    if cc:
        cc = get_email_address_list(cc)
        msg['CC'] = ', '.join(cc)
        recipients = recipients + cc

    if bcc:
        # don't add bcc in header
        bcc = get_email_address_list(bcc)
        recipients = recipients + bcc

    msg['Date'] = formatdate(localtime=True)
    mime_text = MIMEText(html_content, 'html')
    msg.attach(mime_text)

    # Attach files by reading them from disk
    for fname in files or []:
        basename = os.path.basename(fname)
        with open(fname, 'rb') as f:
            msg.attach(
                MIMEApplication(
                    f.read(),
                    Content_Disposition="attachment; filename='%s'" % basename,
                    Name=basename))

    # Attach any files passed directly
    for name, body in (data or {}).items():
        msg.attach(
            MIMEApplication(
                body,
                Content_Disposition="attachment; filename='%s'" % name,
                Name=name,
            ))

    # Attach any inline images, which may be required for display in
    # HTML content (inline)
    for msgid, body in (images or {}).items():
        image = MIMEImage(body)
        image.add_header('Content-ID', '<%s>' % msgid)
        image.add_header('Content-Disposition', 'inline')
        msg.attach(image)

    send_MIME_email(smtp_mail_from, recipients, msg, config, dryrun=dryrun)
コード例 #30
0
ファイル: util_email.py プロジェクト: lcordier/lcutil
def html_email(from_='',
               to=[],
               cc=None,
               bcc=None,
               subject='',
               text_body='',
               html_body='',
               files=None,
               images=[],
               smtp_server='',
               smtp_port=25,
               smtp_username='',
               smtp_password=''):
    """ Generate a HTML email and send it to various recipients via an authenticated SMTP server.

        +-------------------------------------------------------+
        | multipart/mixed                                       |
        |                                                       |
        |  +-------------------------------------------------+  |
        |  |   multipart/related                             |  |
        |  |                                                 |  |
        |  |  +-------------------------------------------+  |  |
        |  |  | multipart/alternative                     |  |  |
        |  |  |                                           |  |  |
        |  |  |  +-------------------------------------+  |  |  |
        |  |  |  | text can contain [cid:logo.png]     |  |  |  |
        |  |  |  +-------------------------------------+  |  |  |
        |  |  |                                           |  |  |
        |  |  |  +-------------------------------------+  |  |  |
        |  |  |  | html can contain src="cid:logo.png" |  |  |  |
        |  |  |  +-------------------------------------+  |  |  |
        |  |  |                                           |  |  |
        |  |  +-------------------------------------------+  |  |
        |  |                                                 |  |
        |  |  +-------------------------------------------+  |  |
        |  |  | image logo.png  "inline" attachement      |  |  |
        |  |  +-------------------------------------------+  |  |
        |  |                                                 |  |
        |  +-------------------------------------------------+  |
        |                                                       |
        |  +-------------------------------------------------+  |
        |  | pdf ("download" attachment, not inline)         |  |
        |  +-------------------------------------------------+  |
        |                                                       |
        +-------------------------------------------------------+

        see: https://www.anomaly.net.au/blog/constructing-multipart-mime-messages-for-sending-emails-in-python/
    """
    message = MIMEMultipart('mixed')

    del message['sender']
    del message['errors-to']
    message['To'] = COMMASPACE.join(to)
    if cc:
        message['Cc'] = COMMASPACE.join(cc)
    message['From'] = from_
    message['Subject'] = subject
    message['Date'] = formatdate(localtime=True)
    message['Message-ID'] = make_msgid()
    message.epilogue = ''

    body = MIMEMultipart('alternative')

    text_part = MIMEText(text_body, 'plain')
    # text_part.set_type('text/plain')
    # text_part.set_charset('iso-8859-1')
    # text_part.replace_header('Content-Transfer-Encoding', 'quoted-printable')
    body.attach(text_part)

    html_part = MIMEText(html_body, 'html')
    body.attach(html_part)

    related = MIMEMultipart('related')
    related.attach(body)

    for count, image in enumerate(images, 1):
        if isinstance(image, basestring):
            with open(image, 'rb') as image_file:
                image_data = image_file.read()
            image_part = MIMEImage(image_data)
            image_filename = os.path.basename(image)
        elif isinstance(image, (tuple)):
            image_part = MIMEImage(image[1])
            image_filename = image[0]

        mime_type = mimetypes.guess_type(image_filename)[0]
        if mime_type:
            image_part.set_type(mime_type)

        image_part.add_header('Content-Location', image_filename)
        image_part.add_header('Content-Disposition',
                              'inline',
                              filename=image_filename)
        image_part.add_header('Content-ID', '<image{}>'.format(count))
        related.attach(image_part)

    message.attach(related)

    if files:
        for attachment in files:
            part = MIMEBase(
                'application',
                'octet-stream')  # 'octet-stream' filtered by MS Exchange.
            with open(attachment, 'rb') as attachment_file:
                attachment_data = attachment_file.read()

            mime_type = mimetypes.guess_type(attachment)[0]
            if mime_type:
                part.set_type(mime_type)

            part.set_payload(attachment_data)
            encode_base64(part)
            part.add_header(
                'Content-Disposition',
                'attachment; filename="%s"' % os.path.basename(attachment))
            message.attach(part)

    smtp = smtplib.SMTP(smtp_server, smtp_port)
    smtp.ehlo()
    smtp.starttls()
    if smtp_username:
        smtp.login(smtp_username, smtp_password)
    if cc:
        to += cc
    if bcc:
        to += bcc
    smtp.sendmail(from_, to, message.as_string())
    smtp.quit()