コード例 #1
0
ファイル: main.py プロジェクト: hofers/contact-form
def contact(request):
    """Handles Contact Form requests.

  Args:
    request (flask.Request): HTTP request object.
  Returns:
    The response text.
  """
    USER = get_secret("seanbot-user")
    PASS = get_secret("seanbot-pass")
    ALLOWED_DOMAINS = get_secret("contact-form-allowed-domains")
    SMTP_DOMAIN = get_secret("smtp-domain")
    SMTP_PORT = get_secret("smtp-port")

    headers = {}
    if request.headers['origin'] in ALLOWED_DOMAINS:
        headers = {'Access-Control-Allow-Origin': request.headers['origin']}

    fields = {}
    data = request.form.to_dict()
    for field in data:
        fields[field] = data[field]

    if not has_required_fields(fields):
        return (f'Missing required fields. Include name email and message.',
                400, headers)

    try:
        msg = MIMEMultipart()
        msg['Subject'] = f'Message from {fields["name"]} via seanhofer.com!'
        msg['From'] = f'"{fields["name"]}" {fields["email"]}'
        msg['To'] = RECIPIENT
        msg.add_header('reply-to', fields["email"])
        msg.attach(MIMEText(fields["message"], 'plain'))
    except Exception as e:
        print("Error constructing message fields: {0}".format(str(e)))
        return ("Error constructing message fields: {0}".format(str(e)), 500,
                headers)

    if "attachments" in fields:
        try:
            b64_files = fields["attachments"].split(',')
            file_names = fields["attachment_names"].split(',')
            for index, b64_file in enumerate(b64_files):
                bytes_file = base64.b64decode(b64_file)
                part = MIMEApplication(bytes_file, Name=file_names[index])
                part[
                    'Content-Disposition'] = f'attachment; filename="{file_names[index]}"'
                msg.attach(part)
        except:
            print("Error attaching attachments. names: {0} attachments: {1}".
                  format(file_names, b64_files))
            return ("Error attaching attachments. names: {0} attachments: {1}".
                    format(file_names, b64_files), 500, headers)

    try:
        context = ssl.create_default_context()
        with smtplib.SMTP_SSL(SMTP_DOMAIN, SMTP_PORT,
                              context=context) as server:
            server.login(USER, PASS)
            server.sendmail(fields["email"], RECIPIENT, msg.as_string())
    except Exception as e:
        print("Error sending email: {0}".format(str(e)))
        return ("Error sending email: {0}".format(str(e)), 500, headers)

    return (f'success: "{msg.as_string()}"', 200, headers)
コード例 #2
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)
コード例 #3
0
def main() -> int:

    main_parser = ArgumentParser(
        description=__doc__,
        formatter_class=ArgumentDefaultsHelpFormatter,
        epilog="{} {}, remember `@arg_file` (see description above)".format(
            __author__, __license__),
        fromfile_prefix_chars="@",
    )

    main_parser.add_argument(
        "csv_file",
        type=FileType(),
        help=
        """CSV file with a header line containing containing the entries. The
        header names can be used inside the template to personalize the messages. Use
        `-` for STDIN.""",
    )
    main_parser.add_argument("subject",
                             type=str,
                             help="Subject of the message")
    main_parser.add_argument(
        "template_file",
        type=FileType(),
        help=
        """Template file for the body of the message. Variables to replace must be
        specified via `${variable}`.""",
    )
    main_parser.add_argument(
        "--hash-file",
        type=Path,
        help="""For every processed mail address write its md5-hash to this file.
        Subsequent runs of this script (with this file passed again) will skip any mail
        address if its hash is inside the file. Lines starting with a `#` are ignored
        and used to write timestamps.""",
    )
    main_parser.add_argument(
        "--no-update",
        action="store_true",
        help="Do not add any hash entries to the `hash-file`",
    )
    mail_args_parser = main_parser.add_argument_group(
        "Email Arguments",
        """Use this arguments to change the header information of the mail, e.g. set
        From: "Jane Doe <*****@*****.**".""",
    )
    mail_args_parser.add_argument(
        "-f",
        "--from",
        nargs=2,
        metavar=("Sender", "From-Mail"),
        required=True,
        dest="from_",
        help=
        """The `From:` to show inside the mail. First part could be your name and
        gets encoded properly. Second part should be your mail-address, can be empty.""",
    )
    mail_args_parser.add_argument("-r",
                                  "--reply-to",
                                  type=str,
                                  help="Reply-To address to set")
    mail_args_parser.add_argument(
        "-a",
        "--attachment",
        # files must be opened and read in binary mode
        type=FileType(mode="br"),
        nargs="+",
        help="Attachments to append to the mail.",
    )
    csv_args_parser = main_parser.add_argument_group(
        "CSV Arguments",
        """Use this arguments to modify the processing of the rows inside the given CSV
        file. In 2018 all female students received a slightly different mail containing
        a flyer for the `movement` mentoring project. You can use the filters for this
        functionality.""",
    )
    csv_args_parser.add_argument(
        "-e",
        "--email-field",
        type=str,
        help=
        "The header of the entry containing the address to send the mail to.",
        default="mail",
    )
    csv_args_parser.add_argument(
        "--filter",
        metavar=("'Field header'", "'RegEx'"),
        nargs=2,
        help="""Filter to apply to the specified field of any entry. Entries
        evaluating to false are skipped. Can be specified multiple times. Use single
        dashes to prevent your shell from expanding *.""",
        action="append",
    )
    csv_args_parser.add_argument(
        "-s",
        "--email-separator",
        default=",",
        help=
        """In case of multiple mail addresses inside the email-field specify their
        separator.""",
    )
    smtp_args_parser = main_parser.add_argument_group(
        "SMTP Arguments",
        """If you would like to test without actually sending any mails set this values
        to localhost:8025 and proceed without authentication and encryption. Then start
        a development server via `python3 -m smtpd -n -c DebuggingServer -u`.""",
    )
    smtp_args_parser.add_argument("--smtp-server",
                                  type=str,
                                  default="localhost",
                                  help="The SMTP server to use")
    smtp_args_parser.add_argument(
        "--smtp-port",
        type=int,
        default=587,
        help="The SMTP port the server is listening on",
    )
    smtp_args_parser.add_argument(
        "--smtp-user",
        type=str,
        default=getuser(),
        help="The username used to connect to the smtp server",
    )
    smtp_args_parser.add_argument(
        "--no-auth",
        action="store_true",
        help="Do not ask for a smtp password and skip authentication attempt",
    )
    smtp_args_parser.add_argument(
        "--no-tls",
        action="store_true",
        help="Do not try to switch to an encrypted connection.",
    )
    verbosity_args_group = main_parser.add_argument_group(
        "Verbosity Arguments",
        """Control the level of messages of the program. All messages beside actual
        output are written to STDERR.""",
    )
    verbosity_args = verbosity_args_group.add_mutually_exclusive_group()
    verbosity_args.add_argument("-d",
                                "--debug",
                                action="store_true",
                                help="Show debug messages")
    verbosity_args.add_argument("-q",
                                "--quiet",
                                action="store_true",
                                help="Show no other messages except")
    verbosity_args_group.add_argument(
        "-l",
        "--log-output",
        type=FileType("a"),
        default=stderr,
        help="Where to write log messages, appending if file already exists.",
    )

    args = main_parser.parse_args()

    def setup_logging(log_level):
        logging.basicConfig(
            level=log_level,
            format=_logging_format,
            stream=args.log_output,
            datefmt=_date_format,
        )

    if args.debug:
        setup_logging(logging.DEBUG)
    elif args.quiet:
        setup_logging(logging.ERROR)
    else:
        setup_logging(logging.INFO)
    logging.debug("Received command line args {}".format(args))

    already_sent_hashes = set()  # type: Set[str]

    # let's see whether any hash file is given and create it if necessary
    if args.hash_file:
        try:
            if args.hash_file.exists():
                with args.hash_file.open() as file:
                    for line in file.readlines():
                        if not line or line.strip().startswith("#"):
                            continue
                        else:
                            already_sent_hashes.add(line.strip())
                logging.info("Processed {} entries from {!r} to skip".format(
                    len(already_sent_hashes), args.hash_file.name))

            else:
                with args.hash_file.open("w") as file:
                    file.write(
                        "# Created {}. See `{} --help` for more information\n".
                        format(now(), argv[0]))
                logging.debug("Created non existent hash-file {!r}".format(
                    args.hash_file.name))
        except PermissionError:
            logging.error(
                "Wrong permissions for hash-file {!r}. Aborting".format(
                    args.hash_file.name))
            return 1
    else:
        logging.warning(
            "No hash file specified to store the mail addresses of the "
            "receivers of this run!")

    try:
        csv_file = DictReader(args.csv_file)
    except csv_error as e:
        logging.error(
            "Could not read template from {}. The following error occurred {}".
            format(args.csv_file.name, e))
        return 1

    logging.debug("Parsed CSV file {!r} with headers {}".format(
        args.csv_file.name, csv_file.fieldnames))

    template = Template(args.template_file.read())

    logging.debug("Constructed template from {!r}.".format(
        args.template_file.name))

    try:
        smtp_conn = SMTP(args.smtp_server, args.smtp_port)
    except ConnectionRefusedError:
        logging.error("Could not connect to server '{}:{}'. "
                      "Please check its address and port number.".format(
                          args.smtp_server, args.smtp_port))
        return 1

    if not args.no_tls:
        try:
            smtp_conn.starttls()
        except SMTPException as e:
            logging.error(
                "Could not switch to STARTTLS connection. Aborting. See `help` "
                "to ignore such errors.")
            return 1
    else:
        logging.info("Skipping switch to encrypted connection as requested.")
    logging.debug("Created connection to server {}".format(args.smtp_server))

    if not args.no_auth:
        try:
            smtp_pass = getpass(prompt="Please enter your smtp password: "******"Received EOF. Cannot continue without password. Exiting")
            return 2
        try:
            smtp_conn.login(args.smtp_user, smtp_pass)
        except (SMTPException, SMTPAuthenticationError) as e:
            logging.error(
                "Could not login with given given password for user {}. "
                "Maybe wrong password?".format(args.smtp_user))
            return 1
        logging.debug("Successfully logged in as {}@{}".format(
            args.smtp_user, args.smtp_server))
    else:
        logging.info("Skipping authentication as requested.")

    first_hash_to_add = True
    for receiver in csv_file:
        logging.debug("Processing entry: {}".format(receiver))
        try:
            entry_identifier = "[{}]".format(receiver[args.email_field])
        except KeyError:
            logging.error(
                "Entry {} contains no address field {}. Aborting.".format(
                    receiver, args.email_field))
            return 1
        # let's check whether any filter are given and skip entry if so
        skip_entry = False
        for field_to_check, regex in args.filter or []:
            try:
                if not match(regex, receiver[field_to_check]):
                    logging.info("{}, failed filter {!r}".format(
                        entry_identifier, regex))
                    skip_entry = True
            except KeyError:
                logging.error(
                    "Cannot apply filter {!r} to nonexistent field {!r}, Aborting."
                    .format(regex, field_to_check))
                return 1
        if skip_entry:
            logging.warning(
                "Skipping {} due to filters.".format(entry_identifier))
            continue
        logging.debug("Constructing mail for {}".format(entry_identifier))
        try:
            body = template.substitute(receiver)
        except KeyError as e:
            logging.error(
                "Template contains an unsubstituted Placeholder: {}. Aborting".
                format(e))
            return 1
        except ValueError as e:
            logging.error(
                "The template contains an error: {!r}. Aborting".format(e))
            return 1
        if args.attachment:
            logging.debug("Processing attachments")
            msg = MIMEMultipart()
            msg.attach(MIMEText(body))
            for attachment in args.attachment:
                attachment_name = attachment.name.split(sep)[-1]
                logging.debug(
                    "Processing attachment {}".format(attachment_name))
                part = MIMEApplication(attachment.read(), Name=attachment_name)
                part[
                    "Content-Disposition"] = 'attachment; filename="{}"'.format(
                        attachment_name)
                msg.attach(part)
                attachment.seek(0)

        else:
            msg = MIMEText(body)  # type: ignore
        msg["From"] = utf8_header(args.from_[0])
        msg["From"].append(" <{}>".format(args.from_[1]), charset="ascii")
        if args.reply_to:
            msg["Reply-To"] = args.reply_to
        msg["Subject"] = utf8_header(args.subject)
        for mail_address in receiver[args.email_field].split(
                args.email_separator):
            mail_address = mail_address.strip()
            msg["To"] = mail_address
            if md5(mail_address) in already_sent_hashes:
                logging.info(
                    "Skipped {} since it is present in the hash-file".format(
                        mail_address))
                continue
            logging.debug("Sending mail to {!r}".format(mail_address))

            try:
                smtp_conn.sendmail(args.smtp_user, mail_address.strip(),
                                   msg.as_string())
            except SMTPException as e:
                logging.critical(
                    "Got unexpected SMTP/Send exception %r. Aborting", e)
                print_traceback_if_requested()
                return 1
            if args.hash_file and not args.no_update:
                with args.hash_file.open("a") as file:
                    if first_hash_to_add:
                        file.write("# Entries from {}\n".format(now()))
                        first_hash_to_add = False
                    file.write("{}\n".format(md5(mail_address)))
                logging.debug(
                    "Added md5-hash of {!r} to hash-file".format(mail_address))

            logging.info("Sent mail to: {!r}".format(mail_address))
    smtp_conn.quit()

    return 0
コード例 #4
0
ファイル: email_utils.py プロジェクト: z756067100/ndscheduler
def send_email(receivers,
               subject,
               content,
               images,
               attachments,
               email_info_file="config/email_info.json"):

    email_file = open(email_info_file)
    emai_info = json.load(email_file)
    sender = emai_info["sender"]
    smtpserver = emai_info["smtpserver"]
    username = emai_info["username"]
    password = emai_info["password"]

    #add the title, from and to
    msg = MIMEMultipart('related')
    msg['Subject'] = Header(subject, 'utf-8')
    msg['from'] = sender
    msg['to'] = ','.join(receivers)

    #add the content into the email
    msgAlternative = MIMEMultipart('alternative')
    msg.attach(msgAlternative)

    mail_msg = ''
    if content != '':
        mail_msg += '{0}{1}{2}'.format('<p>', content, '</p>\n')

    count = 0
    for image in images:
        if image.find('.') != -1:  #it's a file
            mail_msg += '<p><img src="cid:image%d"></p>' % (count)
            count += 1
        else:  #it's a dir
            files = os.listdir(image)
            for file in files:
                mail_msg += '<p><img src="cid:image%d"></p>' % (count)
                count += 1
    msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8'))

    #add the images into the email
    count = 0
    for image in images:
        if image.find('.') != -1:  #it's a file
            msgImage = MIMEImage(open(image, 'rb').read())
            msgImage.add_header('Content-ID', '<image' + str(count) + '>')
            msg.attach(msgImage)
            count += 1
        else:  #it's a dir
            files = os.listdir(image)
            for file in files:
                msgImage = MIMEImage(
                    open('{0}\{1}'.format(image, file), 'rb').read())
                msgImage.add_header('Content-ID', '<image' + str(count) + '>')
                msg.attach(msgImage)
                count += 1

    #add the attachments into the email
    for attachment in attachments:
        if attachment.find('.') != -1:  #it's a file
            att = MIMEApplication(open(attachment, 'rb').read())
            att.add_header('Content-Disposition',
                           'attachment',
                           filename=os.path.split(attachment)[1])
            msg.attach(att)
        else:  #it's a dir
            files = os.listdir(attachment)
            for file in files:
                att = MIMEApplication(
                    open('{0}\{1}'.format(attachment, file), 'rb').read())
                att.add_header('Content-Disposition',
                               'attachment',
                               filename=file)
                msg.attach(att)

    #send email to receivers
    smtp = smtplib.SMTP_SSL('smtp.qq.com', 465)
    smtp.login(username, password)
    smtp.sendmail(sender, receivers, msg.as_string())
    smtp.quit()
コード例 #5
0
    if success:
        # send success notice
        brief = MIMEText("""Hello, %(recipient)s, 

Your request for packaging %(target)s has been received and processed. 
Please find output in attachment.

Thanks,
Packaging Agent""" % dat)
        debug(brief)
        zipname = "%s.%s.zip" % (deliveryType, locale)
        zipfile = open(os.path.join("/tmp", zipname), "rb")
        zipdata = zipfile.read()
        zipfile.close()
        attachment = MIMEApplication(zipdata, "zip")
        attachment.add_header("Content-Disposition",
                              "attachment",
                              filename=zipname)

        msg = MIMEMultipart()
        msg.attach(brief)
        msg.attach(attachment)
    else:
        # send failure notice
        msg = MIMEText("""Hello, %(recipient)s, 

Processing of your request for packaging %(target)s has failed due to 
following reason(s):

%(reason)s
コード例 #6
0
fig = go.Figure(data=data, layout=layout)
offline.plot(fig, filename=busco_plot_name, image='png')

recipients = [str(sys.argv[1])]  #email address provided by the user
emaillist = [elem.strip().split(',') for elem in recipients]
msg = MIMEMultipart()
msg['Subject'] = "Here's your assembly busco plot"
msg['From'] = '*****@*****.**'
msg['Reply-to'] = '*****@*****.**'

msg.preamble = 'Multipart massage.\n'

#body of the email
part = MIMEText(
    "Hi, please find attached the busco plot. BUSCO scores are used to assess genome assembly and annotation completeness with Benchmarking Universal Single-Copy Orthologs. A high quality genome assembly should have higher number of Complete and Single copy genes and lower number of Fragmented and Missing genes. To get more information on the these busco analysis, please visit this link: https://busco.ezlab.org/"
)
msg.attach(part)

part = MIMEApplication(open(busco_plot_name, "rb").read())

#attaches the stacked bar chart html file to the email
part.add_header('Content-Disposition', 'attachment', filename=busco_plot_name)
msg.attach(part)

server = smtplib.SMTP("smtp.gmail.com:587")
server.ehlo()
server.starttls()
server.login("*****@*****.**", "password")

server.sendmail(msg['From'], emaillist, msg.as_string())
コード例 #7
0
    mail: [email protected]<br>
    telegram: @sergsheva<br>
    tel.: +41778154379
  </body>
</html>
"""
attachment = MIMEText(html, 'html')
msg.attach(attachment)

# Attach Job permission to the email
# permission = MIMEApplication(open("Job permission.pdf", "rb").read())
# permission.add_header('Content-Disposition', 'attachment', filename="Job permission.pdf")
# msg.attach(permission)

# Attach Resume to the email
cv = MIMEApplication(open("sergii-shevchenko.cv.pdf", "rb").read())
cv.add_header('Content-Disposition', 'attachment', filename="sergii-shevchenko.cv.pdf")
msg.attach(cv)

# Attach Legitimation card to the email
# card = MIMEApplication(open("sergii-shevchenko.legitimation-card R.pdf", "rb").read())
# card.add_header('Content-Disposition', 'attachment', filename="sergii-shevchenko.legitimation-card R.pdf")
# msg.attach(card)

for email in email_list:
    mail = smtplib.SMTP('smtp.gmail.com', 587)
    mail.ehlo()
    mail.starttls()
    mail.login(my_mail, password)
    mail.sendmail(my_mail, email, msg.as_string())
    mail.quit()
コード例 #8
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)
コード例 #9
0
ファイル: Main.py プロジェクト: phoexer/Kelly
    logging.info("sending file found")
    msg['Subject'] = conf.get('email', 'files_found_subject')
    msg['From'] = conf.get('email', 'send-from')
    msg['To'] = COMMASPACE.join(send_to)
    #msg.preamble = 'Test email'
    
    with open('files_found.html', 'r') as htmlFile:
        files_found = htmlFile.read()
    
    msg.attach(MIMEText(files_found, 'html'))
    
    for src_file in src_files:
        logging.info("Attaching: " + src_file)
        with open(src_file, "rb") as open_file:
            attachment = MIMEApplication(
                open_file.read(),
                Name = os.path.basename(src_file)
            )
        # After the file is closed
        attachment['Content-Disposition'] = 'attachment; filename="%s"' % os.path.basename(src_file)
        logging.info("Attaching: " + str(attachment))
        msg.attach(attachment)
        
    #Finally send email
    sendEmail(msg,conf)
    
    logging.info("Moving processed files to back up")
    
    timestamp = datetime.datetime.now().strftime('%Y-%m-%d_%H%M%S_') 
    for src_file in src_files:
        os.rename(src_file, os.path.abspath(os.path.join(bak_dir, timestamp + os.path.basename(src_file))))
コード例 #10
0
 def add_accessory(self, accessoryfile):
     part = MIMEApplication(open(accessoryfile, 'rb').read())
     part.add_header('Content-Disposition',
                     'attachment',
                     filename=accessoryfile)
     self.msg.attach(part)
コード例 #11
0
ファイル: email.py プロジェクト: CybercentreCanada/airflow
def build_mime_message(
    mail_from: Optional[str],
    to: Union[str, Iterable[str]],
    subject: str,
    html_content: str,
    files: Optional[List[str]] = None,
    cc: Optional[Union[str, Iterable[str]]] = None,
    bcc: Optional[Union[str, Iterable[str]]] = None,
    mime_subtype: str = 'mixed',
    mime_charset: str = 'utf-8',
    custom_headers: Optional[Dict[str, Any]] = None,
) -> Tuple[MIMEMultipart, List[str]]:
    """
    Build a MIME message that can be used to send an email and
    returns full list of recipients.

    :param mail_from: Email address to set as email's from
    :param to: List of email addresses to set as email's to
    :param subject: Email's subject
    :param html_content: Content of email in HTML format
    :param files: List of paths of files to be attached
    :param cc: List of email addresses to set as email's CC
    :param bcc: List of email addresses to set as email's BCC
    :param mime_subtype: Can be used to specify the subtype of the message. Default = mixed
    :param mime_charset: Email's charset. Default = UTF-8.
    :param custom_headers: Additional headers to add to the MIME message.
        No validations are run on these values and they should be able to be encoded.
    :return: Email as MIMEMultipart and list of recipients' addresses.
    """
    to = get_email_address_list(to)

    msg = MIMEMultipart(mime_subtype)
    msg['Subject'] = subject
    msg['From'] = mail_from
    msg['To'] = ", ".join(to)
    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', mime_charset)
    msg.attach(mime_text)

    for fname in files or []:
        basename = os.path.basename(fname)
        with open(fname, "rb") as file:
            part = MIMEApplication(file.read(), Name=basename)
            part['Content-Disposition'] = f'attachment; filename="{basename}"'
            part['Content-ID'] = f'<{basename}>'
            msg.attach(part)

    if custom_headers:
        for header_key, header_value in custom_headers.items():
            msg[header_key] = header_value

    return msg, recipients
コード例 #12
0
msg['To'] = RECIPIENT

# Create a multipart/alternative child container.
msg_body = MIMEMultipart('alternative')

# Encode the text and HTML content and set the character encoding. This step is
# necessary if you're sending a message with characters outside the ASCII range.
textpart = MIMEText(BODY_TEXT.encode(CHARSET), 'plain', CHARSET)
htmlpart = MIMEText(BODY_HTML.encode(CHARSET), 'html', CHARSET)

# Add the text and HTML parts to the child container.
msg_body.attach(textpart)
msg_body.attach(htmlpart)

# Define the attachment part and encode it using MIMEApplication.
att = MIMEApplication(open(ATTACHMENT, 'rb').read())

# Add a header to tell the email client to treat this part as an attachment,
# and to give the attachment a name.
att.add_header('Content-Disposition',
               'attachment',
               filename=os.path.basename(ATTACHMENT))

# Attach the multipart/alternative child container to the multipart/mixed
# parent container.
msg.attach(msg_body)

# Add the attachment to the parent container.
msg.attach(att)
#print(msg)
try:
コード例 #13
0
    def send(self):
        SENDER = "*****@*****.**"
        RECIPIENT = "*****@*****.**"
        AWS_REGION = "us-west-2"
        SUBJECT = "Customer service contact info"
        ATTACHMENT = "demo"
        BODY_TEXT = "Hello,\r\nPlease see the attached file for a list of customers to contact."

        BODY_HTML = """\
          <html>
          <head></head>
          <body>
          <h1>Hello!</h1>
          <p>Please see the attached file for a list of customers to contact.</p>
          </body>
          </html>
          """

        CHARSET = "utf-8"

        # Create a new SES resource and specify a region.
        client = boto3.client('ses', region_name=AWS_REGION)

        # Create a multipart/mixed parent container.
        msg = MIMEMultipart('mixed')
        # Add subject, from and to lines.
        msg['Subject'] = SUBJECT
        msg['From'] = SENDER
        msg['To'] = RECIPIENT

        # Create a multipart/alternative child container.
        msg_body = MIMEMultipart('alternative')

        # Encode the text and HTML content and set the character encoding. This step is
        # necessary if you're sending a message with characters outside the ASCII range.
        textpart = MIMEText(BODY_TEXT.encode(CHARSET), 'plain', CHARSET)
        htmlpart = MIMEText(BODY_HTML.encode(CHARSET), 'html', CHARSET)

        # Add the text and HTML parts to the child container.
        msg_body.attach(textpart)
        msg_body.attach(htmlpart)

        # Define the attachment part and encode it using MIMEApplication.
        att = MIMEApplication(open(ATTACHMENT, 'rb').read())

        # Add a header to tell the email client to treat this part as an attachment,
        # and to give the attachment a name.
        att.add_header('Content-Disposition',
                       'attachment',
                       filename=os.path.basename(ATTACHMENT))

        # Attach the multipart/alternative child container to the multipart/mixed
        # parent container.
        msg.attach(msg_body)
        # import pdb; pdb.set_trace()

        # Add the attachment to the parent container.
        msg.attach(att)
        # print(msg)
        try:
            # Provide the contents of the email.
            response = client.send_raw_email(
                Source=SENDER,
                Destinations=[RECIPIENT],
                RawMessage={
                    'Data': msg.as_string(),
                },
            )
        # Display an error if something goes wrong.
        except ClientError as e:
            print(e.response)
        else:
            print("Email sent! Message ID:"),
            print(response)
コード例 #14
0
 def gzip_part(text):
     return MIMEApplication(gzip_text(text), "gzip")
コード例 #15
0
ファイル: sendEmail.py プロジェクト: ting33/salesReport
msg = MIMEMultipart()
msg["Subject"] = asubject
msg["to"] = areceiver
# msg["Cc"] = acc
msg["from"] = asender

#邮件正文
body = "你好,这是一封测试邮件"

#添加邮件正文
msg.attach(MIMEText(body,'plain','utf-8'))

#添加附件
#注意,这里的文件路径是分割线
filename = "测试文档.xlsx"
xlsxpart = MIMEApplication(open(r'/Users/Desktop/testData/saleReport.txt','rb').read())
xlsxpart.add_header('Content-Disposition', 'attachment',filename="测试文档.xlsx")
msg.attach(xlsxpart)


#设置邮箱服务器地址及端口
smtp_server= "smtp.qq.com"
server = smtplib.SMTP(smtp_server,25)
#打印日志
server.set_debuglevel(1)

#登录邮箱
server.login(from_addr,password)
server.sendmail(from_addr,areceiver.split(",")+acc.split(","),msg.as_string())

#断开服务器连接
コード例 #16
0
ファイル: emailFunc.py プロジェクト: Appelsiini1/haukiposti
def createMail(sender, to, subject, message_html, files):
    """Create a message for an email.

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

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

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

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

                if content_type is None or encoding is not None:
                    content_type = 'application/octet-stream'
                main_type, sub_type = content_type.split('/', 1)
                if main_type == 'text':
                    fp = open(file, 'rb')
                    msg = MIMEText(fp.read(), _subtype=sub_type)
                    fp.close()
                elif main_type == 'image':
                    fp = open(file, 'rb')
                    msg = MIMEImage(fp.read(), _subtype=sub_type)
                    fp.close()
                elif main_type == 'audio':
                    fp = open(file, 'rb')
                    msg = MIMEAudio(fp.read(), _subtype=sub_type)
                    fp.close()
                elif main_type == 'application':
                    fp = open(file, 'rb')
                    msg = MIMEApplication(fp.read(), _subtype=sub_type)
                    fp.close()
                else:
                    fp = open(file, 'rb')
                    msg = MIMEBase(main_type, sub_type)
                    msg.set_payload(fp.read())
                    fp.close()
                filename = os.path.basename(file)
                msg.add_header('Content-Disposition',
                               'attachment',
                               filename=filename)
                message.attach(msg)
    except Exception as e:
        logging.exception(e)
        return -1

    message_as_bytes = message.as_bytes(
    )  # the message should converted from string to bytes.
    message_as_base64 = base64.urlsafe_b64encode(
        message_as_bytes)  #encode in base64 (printable letters coding)
    raw = message_as_base64.decode(
    )  # need to JSON serializable (no idea what does it means)
    return {'raw': raw}
コード例 #17
0
def create_mime(data,maintype='text',subtype=None,charset=None,
    params={}, headers={}, encoding=None):
    """ create MIME message from data.
    if maintype is None, the default content type is text/plain for str,
     and application/octet-stream for binary data.
    The default charset and encoding are automatically detected.
    """
    from email.mime.base import MIMEBase
    from email.mime.application import MIMEApplication
    from email.mime.audio import MIMEAudio
    from email.mime.image import MIMEImage
    from email.mime.message import MIMEMessage
    from email.mime.text import MIMEText
    import email.encoders, six
    if maintype is None:
        if isinstance(data,(six.text_type,)+six.string_types):
            maintype= 'text'
        elif isinstance(data,six.binary_type):
            maintype,subtype = 'application', subtype or 'octet-stream'
    else:
        maintype = maintype.lower()
    cte = 'Content-Transfer-Encoding'
    if maintype=='text':
        subtype = subtype or 'plain'
        data, charset = check_charset(data,charset)
        if encoding is None:
            msg = MIMEText(data, subtype, charset)
        else:
            msg = MIMEText('', subtype, charset)
        if encoding in ('base64','quoted-printable'):
            del msg[cte]
            if not isinstance(data,six.binary_type): data = data.encode(charset)
            msg.set_payload(data)
            if encoding=='base64': email.encoders.encode_base64(msg)
            else: email.encoders.encode_quopri(msg)
        elif encoding:
            if six.PY3:
                from email.policy import default
                policy = default.clone(cte_type='8bit' if encoding=='8bit' else '7bit')
                msg.policy = policy
            msg.replace_header(cte,encoding)
            if encoding=='7bit' and charset!='us-ascii':
                raise UnicodeEncodeError
            if six.PY3 and isinstance(data,six.binary_type): data = data.decode(charset)
            msg.set_payload(data)
        if msg[cte]=='base64': # remove superflous newline
            data = msg.get_payload(decode=False)
            msg.set_payload(data.rstrip())
    else:
        idata = data if encoding else ''
        if maintype=='application': msg = MIMEApplication(idata, subtype, **params)
        elif maintype=='audio': msg = MIMEAudio(idata, subtype, **params)
        elif maintype=='image': msg = MIMEImage(idata, subtype, **params)
        elif maintype=='message': msg = MIMEMessage(idata, subtype)
        else:
            msg = MIMEBase(maintype, subtype, **params)
            encoding = encoding or 'base64'
        if encoding in ('base64','quoted-printable'):
            del msg[cte]
            msg.set_payload(data)
            if encoding=='base64': email.encoders.encode_base64(msg)
            else: email.encoders.encode_quopri(msg)
        elif encoding:
            if six.PY3:
                from email.policy import default
                policy = default.clone(cte_type='7bit' if encoding=='7bit' else '8bit')
                msg.policy = policy
            msg.replace_header(cte,encoding)
            if encoding=='7bit':
                if isinstance(data,six.string_types): data.encode('us-ascii')
                else: data.decode('us-ascii')
            if six.PY3 and isinstance(data,six.binary_type):
                data = data.decode('utf-8','surrogateescape')
            msg.set_payload(data)
        if msg[cte]=='base64': # remove superflous newline
            data = msg.get_payload(decode=False)
            msg.set_payload(data.rstrip())
    for k, v in six.iteritems(headers):
        _set_header(msg,k,v)
    return msg
コード例 #18
0
ファイル: alarmfunctionsr.py プロジェクト: pratikv/pvrpi
def SendEmailAlertThread(SensorNumber, smartruleid, ruleind, photo):
    
        # Get the email addresses that you configured on the server
        RecordSet = GetDataFromHost(5,[0])
        if RecordSet==False:
                return
        
        numrows = len(RecordSet)
        
        if globals.smtp_server=="":
                return
        
        if ruleind:
                msgtext = BuildMessageFromRule(SensorNumber, smartruleid)
        else:
                msgtext = BuildMessage(SensorNumber)
                
        for i in range(numrows):
                # Define email addresses to use
                addr_to   = RecordSet[i][0]
                addr_from = globals.smtp_user #Or change to another valid email recognized under your account by your ISP      
                # Construct email
                
                if (photo==1):
                        files = 0
                        files = glob.glob(globals.photopath)
                        latestphoto = get_latest_photo(files)
                        msg = MIMEMultipart()
                else:
                        msg = MIMEText(msgtext)
                
                msg['To'] = addr_to
                msg['From'] = addr_from
                msg['Subject'] = 'Alarm Notification' #Configure to whatever subject line you want
                
                #attach photo
                if (photo==1):
                        msg.preamble = 'Multipart message.\n'  
                        part = MIMEText(msgtext) 
                        msg.attach(part)
                        part = MIMEApplication(open(latestphoto,"rb").read())
                        part.add_header('Content-Disposition', 'attachment', filename=latestphoto)
                        msg.attach(part)
                
                # Send the message via an SMTP server
                
                #Option 1 - No Encryption
                if globals.email_type==1:
                        s = smtplib.SMTP(globals.smtp_server)
                elif globals.email_type==2:
                #Option 2 - SSL
                        s = smtplib.SMTP_SSL(globals.smtp_server, 465)
                elif globals.email_type==3:
                #Option 3 - TLS
                        s = smtplib.SMTP(globals.smtp_server,587)
                        s.ehlo()
                        s.starttls()
                        s.ehlo()
                else:
                        s = smtplib.SMTP(globals.smtp_server)
                        
                
                s.login(globals.smtp_user,globals.smtp_pass)
                s.sendmail(addr_from, addr_to, msg.as_string()) 
                s.quit()
                if globals.PrintToScreen: print msg;
コード例 #19
0
ファイル: mail.py プロジェクト: yikehd/seldom
    def sender(self, to=None, subject=None, contents=None, attachments=None):
        if to is None:
            raise ValueError("Please specify the email address to send")

        if subject is None:
            subject = 'Seldom Test Report'
        if contents is None:
            contents = """
            <table width="50%" cellpadding="0" cellspacing="0"
                style="font-family:'Helvetica Neue',Helvetica,Arial,sans-serif;box-sizing:border-box;display:inline-block;font-size:14px;overflow:hidden;border-radius:7px;background-color:##f5f9fc;margin:0;border:1px solid #e9e9e9"
                bgcolor="#f5f9fc">
                <tbody>
                    <tr
                        style="font-family:'Helvetica Neue',Helvetica,Arial,sans-serif;box-sizing:border-box;font-size:14px;margin:0">
                        <td style="font-family:'Helvetica Neue',Helvetica,Arial,sans-serif;box-sizing:border-box;font-size:16px;vertical-align:top;color:#fff;font-weight:500;text-align:center;border-radius:3px 3px 0 0;background-color:#47bac1;margin:0;padding:20px"
                            align="center" bgcolor="#354052" valign="top">
                            <span style="margin-top:20px;display:block"> Seldom Test Report </span>
                        </td>
                    </tr>
                    <tr
                        style="font-family:'Helvetica Neue',Helvetica,Arial,sans-serif;box-sizing:border-box;font-size:14px;margin:0">
                        <td style="font-family:'Helvetica Neue',Helvetica,Arial,sans-serif;box-sizing:border-box;font-size:14px;vertical-align:top;margin:0;padding:20px"
                            valign="top">
                            <font color="#888888">
                            </font>
                            <font color="#888888">

                            </font>
                            <table width="100%" cellpadding="0" cellspacing="0"
                                style="font-family:'Helvetica Neue',Helvetica,Arial,sans-serif;box-sizing:border-box;font-size:14px;margin:0">

                                <tbody>
                                    <tr
                                        style="font-family:'Helvetica Neue',Helvetica,Arial,sans-serif;box-sizing:border-box;font-size:14px;margin:0">
                                        <td style="font-family:'Helvetica Neue',Helvetica,Arial,sans-serif;box-sizing:border-box;font-size:14px;vertical-align:top;margin:0;padding:0 0 20px"
                                            valign="top">
                                            通过用例: {mail_pass}
                                        </td>
                                    </tr>

                                    <tr
                                        style="font-family:'Helvetica Neue',Helvetica,Arial,sans-serif;box-sizing:border-box;font-size:14px;margin:0">
                                        <td style="font-family:'Helvetica Neue',Helvetica,Arial,sans-serif;box-sizing:border-box;font-size:14px;vertical-align:top;margin:0;padding:0 0 20px"
                                            valign="top">
                                            失败用例: {mail_fail}
                                        </td>
                                    </tr>

                                    <tr
                                        style="font-family:'Helvetica Neue',Helvetica,Arial,sans-serif;box-sizing:border-box;font-size:14px;margin:0">
                                        <td style="font-family:'Helvetica Neue',Helvetica,Arial,sans-serif;box-sizing:border-box;font-size:14px;vertical-align:top;margin:0;padding:0 0 20px"
                                            valign="top">
                                            错误用例: {mail_error}
                                        </td>
                                    </tr>

                                    <tr
                                        style="font-family:'Helvetica Neue',Helvetica,Arial,sans-serif;box-sizing:border-box;font-size:14px;margin:0">
                                        <td style="font-family:'Helvetica Neue',Helvetica,Arial,sans-serif;box-sizing:border-box;font-size:14px;vertical-align:top;margin:0;padding:0 0 20px"
                                            valign="top">
                                            跳过用例: {mail_skip}
                                        </td>
                                    </tr>   
                                </tbody>
                            </table>
                            <font color="#888888">
                            </font>
                        </td>
                    </tr>
                </tbody>
            </table>
            """.format(mail_pass=str(RunResult.passed), 
                       mail_fail=str(RunResult.failed),
                       mail_error=str(RunResult.errors),
                       mail_skip=str(RunResult.skiped))
        
        msg = MIMEMultipart()
        msg['Subject'] = Header(subject, 'utf-8')
        msg['From'] = self.user
        msg['To'] = to

        text = MIMEText(contents, 'html', 'utf-8')
        msg.attach(text)

        if attachments is None:
            attachments = BrowserConfig.report_path

        att_name = "report.html"
        if "\\" in attachments:
            att_name = attachments.split("\\")[-1]
        if "/" in attachments:
            att_name = attachments.split("/")[-1]

        att = MIMEApplication(open(attachments, 'rb').read())
        att['Content-Type'] = 'application/octet-stream'
        att["Content-Disposition"] = 'attachment; filename="{}"'.format(att_name)
        msg.attach(att)

        smtp = smtplib.SMTP()
        smtp.connect(self.host)
        smtp.login(self.user, self.password)
        smtp.sendmail(self.user, to, msg.as_string())
        smtp.quit()
        log.info("Email sent successfully!!")
コード例 #20
0
# 第一步:连接邮箱的smtp服务器,并登录
smtp = smtplib.SMTP_SSL(host="smtp.qq.com", port=465)
smtp.login(user="******", password="******")

# 第二步:构建一封邮件
# 创建一封多组件的邮件
msg = MIMEMultipart()

with open("report1.html", "rb") as f:
    content = f.read()
# 创建邮件文本内容
text_msg = MIMEText(content, _subtype="html", _charset="utf8")
# 添加到多组件的邮件中
msg.attach(text_msg)
# 创建邮件的附件
report_file = MIMEApplication(content)
report_file.add_header('content-disposition',
                       'attachment',
                       filename='26report.html')
# 将附件添加到多组件的邮件中
msg.attach(report_file)

# 主题
msg["Subject"] = "26期上课发送邮件"
# 发件人
msg["From"] = "*****@*****.**"
# 收件人
msg["To"] = "*****@*****.**"

# 第三步:发送邮箱
smtp.send_message(msg,
コード例 #21
0
ファイル: MailSend.py プロジェクト: muongroup/openCV
# 送受信先
to_email = "*********@gmail.com"
from_email = "********@gmail.com"

# MIMEの作成
subject = "Pump Room Image"
message = "Look at these."
msg = MIMEMultipart()
msg["Subject"] = subject
msg["To"] = to_email
msg["From"] = from_email
msg.attach(MIMEText(message))

# ファイルを添付
path = "./image_comp.zip"
with open(path, "rb") as f:
    part = MIMEApplication(
        f.read(),
        Name=basename(path)
    )

part['Content-Disposition'] = 'attachment; filename="%s"' % basename(path)
msg.attach(part)

# メール送信処理
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(account, password)
server.send_message(msg)
server.quit()
コード例 #22
0
ファイル: fpemail.py プロジェクト: esizer/fpscanlite
	def send(self):

		self.prepare_zip()

		vulnerable_sites = 0

		d = datetime.datetime.now()
		date = d.strftime("%A, %B %d, %Y at %H:%M")
		send_to = self.config.get("email", "to")
		send_from = self.config.get("email", "from")
		subject = self.config.get("email", "subject")

		text = "<h2>FP Scan completed (" + date + ")</h2>"

		if self.vuns is not None:
			vuns_string = "<br />"
			for i, v in self.vuns.items():

				if len(v) > 0:
					vulnerable_sites = vulnerable_sites + 1
					vuns_string = vuns_string + "<li><strong>%s</strong><ul>" % (i)
					for p in v:
						vuns_string = vuns_string + "<li>%s</li>" % (p)
					vuns_string = vuns_string + "</ul></li>"
			new_text = """
				<span style=\"color:#FF0000;\">
					We found <strong>{0}</strong> site(s) with vunerabilities
					</span>:
					<ul>
					{1}
					</ul>
			""".format(vulnerable_sites, vuns_string)
			text = text + new_text
		else:
			text = text + "<img src=\"http://floating-point.com/fpscan.jpg\" alt=\"No Vunerabilities Found\" />"

		if ',' in send_to:
			print "multiple emails"
			send_to = send_to.split(",")
			send_to = ", ".join(send_to)

		msg = MIMEMultipart()
		msg['Subject'] = subject
		msg['From'] = send_from
		msg['To'] = send_to
		msg['Date'] = formatdate(localtime=True)

		msg.attach(MIMEText(text, 'html'))

		if self.file is not None:
			with open(self.file, "rb") as f:
				msg.attach(MIMEApplication(
					f.read(),
					Content_Disposition='attachment; filename="%s"' % f,
					Name="site_results.zip"
				))

		server = self.config.get("email", "smtp")
		smtp = smtplib.SMTP(server)
		smtp.sendmail(send_from, send_to, msg.as_string())
		smtp.close()
コード例 #23
0
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

# 总的邮件内容,分为不同的模块
msg_total = MIMEMultipart()
msg_total['Subject'] = 'hello'

# 正文模块
msg_raw = """<p style="color:red">你好</p>
"""
msg = MIMEText(msg_raw, 'html')
msg_total.attach(msg)

# 附件模块
mfile = MIMEApplication(open('demo.txt', 'rb').read())
# 添加附件的头信息
mfile.add_header('Content-Disposition', 'attachment', filename='demo')
# 附件摸快添加到总的里面
msg_total.attach(mfile)

with smtplib.SMTP_SSL('smtp.163.com', 465) as server:
    # 登录
    server.login(emailname, emailpwd)
    # msg = '''\\
    # From: yuze
    # Subject: test
    #
    # This is a test'''

    # 发送邮件
コード例 #24
0
ファイル: Mail.py プロジェクト: idreamboat/JDMonitor
    def SendMailFile(self,filename,MessageSource,FromUserName,FileSize,CreatTime):
        CreatTime=datetime.datetime.fromtimestamp(CreatTime)
        FileSize=int(FileSize)
        if FileSize>1024**3:
            FileSize=str(FileSize/(1024**3))+'GB'
        elif FileSize>1024**2:
            FileSize=str(FileSize/(1024**2))+'MB'
        elif FileSize>1024:
            FileSize=str(FileSize/(1024))+'KB'
        else:
            FileSize=str(FileSize)+'B'
        sender = '**@163.com'
        passWord = '******'
        mail_host = 'smtp.163.com'
        # receivers是邮件接收人,用列表保存,可以添加多个
        receivers = ['**@qq.com']

        # 设置email信息
        msg = MIMEMultipart()
        # 邮件主题
        msg['Subject'] = Header('WeChat File','utf-8').encode()
        # 发送方信息
        msg['From'] = self._format_addr('Admin')
        # 邮件正文是MIMEText:
        msg_content = '已收到微信文件,请马上查看!详情如下:\n来源:{}\n发送者:{}\n文件名:{}\n大小:{}\n发送时间:{}\n'.format(MessageSource,FromUserName,filename,FileSize,CreatTime)
        # 简单文本到正文,plain
        msg.attach(MIMEText(msg_content, 'plain', 'utf-8'))
        # # 将附件图片嵌入正文,html
        # msg.attach(MIMEText('<html><body><h1>尽快扫码吧!</h1>' + '<p><img src="cid:0"></p>' + '</body></html>', 'html', 'utf-8'))

        # 添加附件方法一(基本不可取)
        # with open(filename,'rb') as f:
        #     mime = MIMEBase('application','octet-stream')
        #     # 加上必要的头信息:
        #     mime.add_header('Content-Disposition', 'attachment', filename=filename)#中文名乱码,英文名没问题,文件内容乱码
        #     # mime.add_header('Content-Disposition', 'attachment', filename=('gbk','',filename))#只是文件内容乱码
        #     # mime.add_header('Content-Disposition', 'attachment', filename="%s"%os.path.basename(filename))#中文名乱码,另外内容都乱码
        #     mime.set_payload(f.read())
        #     encoders.encode_base64(mime)
        #     # 添加到MIMEMultipart:
        #     msg.attach(mime)

        # 添加附件方法二
        with open(filename,'rb') as f:
            mime=MIMEApplication(f.read())
            # mime.add_header('Content-Disposition', 'attachment', filename=('gbk','',filename))   gbk,utf-8,unicode遇到中文直接报错
            # mime.add_header('Content-Disposition', 'attachment', filename=filename)#中文名 tcmime.2344.2546.20297.bin
            mime.add_header('Content-Disposition', 'attachment', filename="%s"%Header(filename,'utf-8').encode())#成功
            msg.attach(mime)

        # 登录并发送邮件
        try:
            # 163smtp服务器的端口号为465或
            s = smtplib.SMTP_SSL("smtp.163.com", 465)
            s.set_debuglevel(1)
            s.login(sender, passWord)
            # 给receivers列表中的联系人逐个发送邮件
            for item in receivers:
                msg['To'] = to =self._format_addr(item)
                s.sendmail(sender, to, msg.as_string())
                # print('Success!')
            s.quit()
            # print("All emails have been sent over!")
        except smtplib.SMTPException as e:
            print("Falied,%s", e)
コード例 #25
0
ファイル: sendEmail.py プロジェクト: uk45h/pythonPi
import smtplib
import sys
import os
import time


os.system('raspistill -o ruch.jpg --exposure auto  --timeout 1 -q 100 -w 1920 -h 1080')
time.sleep(3)    
recipients = ['*****@*****.**'] 
emaillist = [elem.strip().split(',') for elem in recipients]
msg = MIMEMultipart()
msg['Subject'] = str(sys.argv[1])
msg['From'] = '*****@*****.**'
msg['Reply-to'] = '*****@*****.**'
 
msg.preamble = 'Multipart massage.\n'
 
part = MIMEText("Zdjecie mieszkania w zalaczniku")
msg.attach(part)
 
part = MIMEApplication(open(str(sys.argv[2]),"rb").read())
part.add_header('Content-Disposition', 'attachment', filename=str(sys.argv[2]))
msg.attach(part)
 

server = smtplib.SMTP("smtp.gmail.com:587")
server.ehlo()
server.starttls()
server.login("*****@*****.**", "1qazXSW@")
 
server.sendmail(msg['From'], emaillist , msg.as_string())
コード例 #26
0
  msg = MIMEMultipart()
  msg['From'] = me
  msg['To'] = you
  msg['Date'] = formatdate(localtime=True)
  msg['Subject'] = "Math Advising (%s): %s Course Selection" % (student.ID, termtext)
  msg.attach(MIMEText(body))

  # add attachments
  allattach = [pdfreport]
  allattach.extend(myattach)
  print(allattach)
  for f in allattach:
    with open(f, "rb") as fil:
      msg.attach(MIMEApplication(
        fil.read(),
        Content_Disposition='attachment; filename="%s"' % basename(f),
        Name=basename(f)
      ))

  # send message
  if(len(sys.argv) > 1 and sys.argv[1] == '--run'):
    try:
      smtp.sendmail(me, [you], msg.as_string())
      print("Successfully sent email to %s" % (student.email))
    except SMTPException:
      print("Error: unable to send email to %s" % (student.email))
  else:
    print(body)


コード例 #27
0
    def create_email_message(self,
                             fromaddr,
                             toaddrs,
                             ccaddrs,
                             subject,
                             priority,
                             include_userdata=False,
                             stack_trace="",
                             comments="",
                             include_environment=True):
        """ Format a bug report email from the log files.
        """
        from email.mime.application import MIMEApplication
        from email.mime.multipart import MIMEMultipart
        from email.mime.text import MIMEText

        message = MIMEMultipart()
        message['Subject'] = "%s [priority=%s]" % (subject, priority)
        message['To'] = ', '.join(toaddrs)
        message['Cc'] = ', '.join(ccaddrs)
        message['From'] = fromaddr
        message.preamble = 'You will not see this in a MIME-aware mail ' \
            'reader.\n'
        message.epilogue = ' '  # To guarantee the message ends with a newline

        # First section is simple ASCII data ...
        m = []
        m.append("Bug Report")
        m.append("==============================")
        m.append("")

        if len(comments) > 0:
            m.append("Comments:")
            m.append("========")
            m.append(comments)
            m.append("")

        if len(stack_trace) > 0:
            m.append("Stack Trace:")
            m.append("===========")
            m.append(stack_trace)
            m.append("")

        msg = MIMEText('\n'.join(m))
        message.attach(msg)

        # Include the log file ...
        logtext = self.whole_log_text()
        msg = MIMEText(logtext)
        msg.add_header('Content-Disposition',
                       'attachment',
                       filename='logfile.txt')
        message.attach(msg)

        # Include the environment variables ...
        # FIXME: ask the user, maybe?
        if include_environment:
            # Transmit the user's environment settings as well.  Main purpose is
            # to work out the user name to help with following up on bug reports
            # and in future we should probably send less data.
            entries = []
            for key, value in sorted(os.environ.items()):
                entries.append('%30s : %s\n' % (key, value))

            msg = MIMEText(''.join(entries))
            msg.add_header('Content-Disposition',
                           'attachment',
                           filename='environment.txt')
            message.attach(msg)

        if include_userdata and len(self.mail_files) != 0:
            f = StringIO()
            zf = zipfile.ZipFile(f, 'w')
            for mf in self.mail_files:
                mf(zf)
            zf.close()

            msg = MIMEApplication(f.getvalue())
            msg.add_header('Content-Disposition',
                           'attachment',
                           filename='userdata.zip')
            message.attach(msg)

        return message
コード例 #28
0
ファイル: email.py プロジェクト: AlgernonSolutions/leech
 def _create_attachments(cls, attachment: object, **kwargs):
     attachment_type = kwargs.get('attachment_type', 'data.csv')
     att = MIMEApplication(attachment)
     att.add_header("Content-Disposition", "attachment", filename=attachment_type)
     return att
コード例 #29
0
ファイル: smtp_new.py プロジェクト: ziyi21/python_project
def Send_email_text(subject, content, filepath, receive_email):
    # sender = "*****@*****.**"
    sender = "*****@*****.**"
    passwd = "kong368534"
    receivers = receive_email  # 收件人邮箱

    msgRoot = MIMEMultipart()

    msgRoot['From'] = sender
    msgRoot['To'] = receivers

    # if len(receivers) > 1:
    # 	# msgRoot['To'] = receivers[0]  # 群发邮件
    # 	msgRoot['To'] = receivers[0]
    # 	msgRoot['CC'] = receivers[1]
    # 	# msgRoot['Bcc'] = ','.join(receivers[2:])
    # else:
    # 	msgRoot['To'] = receivers[0]

    #     添加图片
    fp = open('data/img/有你Offer公众号.jpg', 'rb')
    msgImage = MIMEImage(fp.read())
    fp.close()
    msgImage.add_header('Content-ID', '<image1>')
    msgRoot.attach(msgImage)

    msgRoot['Subject'] = subject
    part = MIMEText(content)
    msgRoot.attach(part)

    # html格式构造
    html = """
            <html> 
              <head></head> 
              <body> 
                  <p>
                    %s
                   <br><img src="cid:image1"></br> 
                  </p>
              </body> 
            </html> 
            """ % (content)
    htm = MIMEText(html, 'html', 'utf-8')
    msgRoot.attach(htm)

    ##添加附件部分
    for path in filepath:
        if ".jpg" in path or ".png" in path:
            # jpg类型附件
            jpg_name = path.split("/")[-1]
            part = MIMEApplication(open(path, 'rb').read())
            part.add_header('Content-Disposition',
                            'attachment',
                            filename=('gbk', '', jpg_name))
            msgRoot.attach(part)

        if ".pdf" in path:
            # pdf类型附件
            pdf_name = path.split("/")[-1]
            part = MIMEApplication(open(path, 'rb').read())
            part.add_header('Content-Disposition',
                            'attachment',
                            filename=pdf_name)
            msgRoot.attach(part)

        if ".xlsx" in path:
            # xlsx类型附件
            xlsx_name = path.split("/")[-1]
            part = MIMEApplication(open(path, 'rb').read())
            # part.add_header('Content-Disposition', 'attachment', filename=xlsx_name)
            part.add_header('Content-Disposition',
                            'attachment',
                            filename=('gbk', '', xlsx_name))
            # encoders.encode_base64(part)
            msgRoot.attach(part)

        if ".txt" in path:
            # txt类型附件
            txt_name = path.split("/")[-1]
            part = MIMEApplication(open(path, 'rb').read())
            # part.add_header('Content-Disposition', 'attachment', filename=txt_name)
            part.add_header('Content-Disposition',
                            'attachment',
                            filename=('gbk', '', txt_name))
            encoders.encode_base64(part)
            msgRoot.attach(part)

        if ".mp3" in path:
            # mp3类型附件
            mp3_name = path.split("/")[-1]
            part = MIMEApplication(open(path, 'rb').read())
            part.add_header('Content-Disposition',
                            'attachment',
                            filename=mp3_name)
            msgRoot.attach(part)

    try:
        # s = smtplib.SMTP()
        # s.set_debuglevel(1)
        # print(msgRoot.as_string())
        s = smtplib.SMTP()
        s.connect("smtp.163.com")  # 这里我使用的是阿里云邮箱,也可以使用163邮箱:smtp.163.com
        s.login(sender, passwd)
        s.sendmail(sender, receivers, msgRoot.as_string())
        print("邮件发送成功")
    except smtplib.SMTPException as e:
        print(e)
        print("Error, 发送失败")
    finally:
        s.quit()
コード例 #30
0
ファイル: soap.py プロジェクト: mnlipp/CoCy
def apply_mtom(headers, envelope, params, paramvals):
    '''
    Apply MTOM to a SOAP envelope, separating attachments into a
    MIME multipart message.

    References:
    XOP     http://www.w3.org/TR/xop10/
    MTOM    http://www.w3.org/TR/soap12-mtom/
            http://www.w3.org/Submission/soap11mtom10/

    @param headers   Headers dictionary of the SOAP message that would
                     originally be sent.
    @param envelope  SOAP envelope string that would have originally been sent.
    @param params    params attribute from the Message object used for the SOAP
    @param paramvals values of the params, passed to Message.to_xml
    @return          tuple of length 2 with dictionary of headers and
                     string of body that can be sent with HTTPConnection
    '''

    # grab the XML element of the message in the SOAP body
    soaptree = etree.ElementTree.fromstring(envelope)
    soapbody = soaptree.find("{%s}Body" % cocy.soaplib.ns_soap_env)

    message = None
    for child in list(soapbody):
        if child.tag != "%sFault" % (soaplib.ns_soap_env, ):
            message = child
            break

    # Get additional parameters from original Content-Type
    ctarray = []
    for n, v in headers.items():
        if n.lower() == 'content-type':
            ctarray = v.split(';')
            break
    roottype = ctarray[0].strip()
    rootparams = {}
    for ctparam in ctarray[1:]:
        n, v = ctparam.strip().split('=')
        rootparams[n] = v.strip("\"'")

    # Set up initial MIME parts.
    mtompkg = MIMEMultipart('related',
                            boundary='?//<><>soaplib_MIME_boundary<>')
    rootpkg = None
    try:
        rootpkg = MIMEApplication(envelope, 'xop+xml', encode_7or8bit)
    except NameError:
        rootpkg = MIMENonMultipart("application", "xop+xml")
        rootpkg.set_payload(envelope)
        encode_7or8bit(rootpkg)

    # Set up multipart headers.
    del (mtompkg['mime-version'])
    mtompkg.set_param('start-info', roottype)
    mtompkg.set_param('start', '<soaplibEnvelope>')
    if 'SOAPAction' in headers:
        mtompkg.add_header('SOAPAction', headers.get('SOAPAction'))

    # Set up root SOAP part headers.
    del (rootpkg['mime-version'])

    rootpkg.add_header('Content-ID', '<soaplibEnvelope>')

    for n, v in rootparams.items():
        rootpkg.set_param(n, v)

    rootpkg.set_param('type', roottype)

    mtompkg.attach(rootpkg)

    # Extract attachments from SOAP envelope.
    for i in range(len(params)):
        name, typ = params[i]

        if typ == Attachment:
            id = "soaplibAttachment_%s" % (len(mtompkg.get_payload()), )

            param = message[i]
            param.text = ""

            incl = etree.ElementTree.SubElement(
                param, "{%s}Include" % cocy.soaplib.ns_xop)
            incl.attrib["href"] = "cid:%s" % id

            if paramvals[i].fileName and not paramvals[i].data:
                paramvals[i].load_from_file()

            data = paramvals[i].data
            attachment = None

            try:
                attachment = MIMEApplication(data, _encoder=encode_7or8bit)

            except NameError:
                attachment = MIMENonMultipart("application", "octet-stream")
                attachment.set_payload(data)
                encode_7or8bit(attachment)

            del (attachment['mime-version'])

            attachment.add_header('Content-ID', '<%s>' % (id, ))
            mtompkg.attach(attachment)

    # Update SOAP envelope.
    rootpkg.set_payload(etree.ElementTree.tostring(soaptree))

    # extract body string from MIMEMultipart message
    bound = '--%s' % (mtompkg.get_boundary(), )
    marray = mtompkg.as_string().split(bound)
    mtombody = bound
    mtombody += bound.join(marray[1:])

    # set Content-Length
    mtompkg.add_header("Content-Length", str(len(mtombody)))

    # extract dictionary of headers from MIMEMultipart message
    mtomheaders = {}
    for name, value in mtompkg.items():
        mtomheaders[name] = value

    if len(mtompkg.get_payload()) <= 1:
        return (headers, envelope)

    return (mtomheaders, mtombody)