Пример #1
0
    def test_encoding_multipart(self):
        from email.mime import application
        from email.mime import multipart
        from email.mime import nonmultipart
        from repoze.sendmail._compat import b
        from repoze.sendmail._compat import encodestring
        from repoze.sendmail._compat import from_octets

        message = multipart.MIMEMultipart('alternative')

        utf_8_encoded = b('mo \xe2\x82\xac')
        utf_8 = utf_8_encoded.decode('utf-8')

        plain_string = utf_8
        plain_part = nonmultipart.MIMENonMultipart('plain', 'plain')
        plain_part.set_payload(plain_string)
        message.attach(plain_part)

        html_string = '<p>' + utf_8 + '</p>'
        html_part = nonmultipart.MIMENonMultipart('text', 'html')
        html_part.set_payload(html_string)
        message.attach(html_part)

        binary = from_octets([x for x in range(256)])
        binary_b64 = encodestring(binary)
        binary_part = application.MIMEApplication(binary)
        message.attach(binary_part)

        encoded = self._callFUT(message)

        self.assertTrue(encodestring(plain_string.encode('utf-8')) in encoded)
        self.assertTrue(encodestring(html_string.encode('utf-8')) in encoded)
        self.assertTrue(binary_b64 in encoded)
Пример #2
0
def sender_mail():
    smt_p = smtplib.SMTP()  # 创建对象
    smt_p.connect(host='smtp.qq.com', port=25)  # 设置smtp服务器
    sender = '*****@*****.**'
    password = "******"  # 在qq邮箱设置开启SMTP服务并复制授权码到password
    smt_p.login(sender, password)  # 进行邮箱登录一次,填写你本人的邮箱
    receiver_addresses, count_num = [
        '*****@*****.**', '*****@*****.**'
    ], 1
    for email_address in receiver_addresses:
        # 表格中邮箱格式不正确,如有空字符,在发邮件的时候会出现异常报错,捕获到这些异常就跳过
        try:
            msg = multipart.MIMEMultipart()
            msg['From'] = "zhenguo"  # 设置发邮件人
            msg['To'] = email_address  # 收件人
            # msg['Cc'] = '*****@*****.**'
            msg['subject'] = header.Header('通知', 'utf-8')  # 主题名称
            msg.attach(
                text.MIMEText(
                    '您好!\n这是一封测试邮件,使用Python实现自动发邮件,请勿回复本邮件功能~\n\n  祝您工作愉快!',
                    'plain', 'utf-8'))
            xlsxpart = application.MIMEApplication(
                open(r'./data/email_test.xlsx', 'rb').read())
            xlsxpart.add_header('Content-Disposition',
                                'attachment',
                                filename='1.xlsx')
            msg.attach(xlsxpart)  # 添加邮件的附件
            smt_p.sendmail(sender, email_address, msg.as_string())  # 发送邮件
            time.sleep(10)  # sleep10秒避免发送频率过快,可能被判定垃圾邮件。
            print('第%d次发送给%s' % (count_num, email_address))
            count_num = count_num + 1
        except Exception as e:
            print('第%d次给%s发送邮件异常' % (count_num, email_address))
            continue
    smt_p.quit()
Пример #3
0
def send_mail(send_from, send_to, subject, text, filename=None):
    msg = emm.MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = send_to
    msg['Date'] = eu.formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach(emt.MIMEText(text))

    # Attach the given file.
    if filename is not None:
        with open(filename, "rb") as f:
            part = ema.MIMEApplication(f.read(), Name=os.path.basename(f))

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

    # Get the recipient MX record.
    domain = send_to.split('@')[1]
    server = get_mx_record(domain)
    smtp = smtplib.SMTP(server)

    # Send
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()
Пример #4
0
def create_pdf_attachment(filename):
    file = open(filename, "rb")
    attachment = application.MIMEApplication(file.read(), _subtype="pdf")
    file.close()
    attachment.add_header("Content-Disposition",
                          "attachement",
                          filename=filename)
    return attachment
Пример #5
0
def send_email(smtp_host,
               smtp_port,
               send_addr,
               password,
               recipient_addrs,
               path,
               subject='',
               content=''):
    """
        send email
    :param smtp_host:smpt.gmail.com
    :param smtp_port:587
    :param send_addr:
    :param password:
    :param recipient_addrs:
    :param path:
    :param subject: title
    :param content: content
    :return:None
    """
    msg = email.mime.multipart.MIMEMultipart()
    msg['from'] = email.utils.formataddr(["cve-manager", send_addr])
    msg['to'] = recipient_addrs
    msg['subject'] = subject
    content = content
    txt = email.mime.text.MIMEText(content, 'plain', 'utf-8')
    msg.attach(txt)
    # Add attachment address
    files = os.listdir(path)
    if not files:
        print("No data sheet")
        return
    for fileName in files:
        part = application.MIMEApplication(
            open(path + '/' + fileName, 'rb').read())
        part.add_header('Content-Disposition', 'attachment', filename=fileName)
        msg.attach(part)
    try:
        smtp_ssl_client = smtplib.SMTP(smtp_host, smtp_port)
        # smtp_ssl_client.ehlo()
        # smtp_ssl_client.starttls()
        # login_res = smtp_ssl_client.login(send_addr, password)
        # print("Login result:login_res=", login_res)
        # if login_res and login_res[0] == 235:
        #     print("login successful,code=[login_res[0]]")
        #     smtp_ssl_client.sendmail(send_addr, recipient_addrs, str(msg))
        #     print("mail has been send successfully. message: ", str(msg))
        #     smtp_ssl_client.quit()
        # else:
        #     print("login failed,code= ", login_res[0])
        smtp_ssl_client.sendmail(send_addr, recipient_addrs, str(msg))
        print("mail has been send successfully. message: ", str(msg))
        smtp_ssl_client.quit()
    except SystemExit as e:
        print("Failed to send,Exception:e= ", e)
Пример #6
0
    def test_binary_body(self):
        from email.mime import application
        from email.mime import multipart
        from repoze.sendmail._compat import encodestring
        from repoze.sendmail._compat import b
        body = b('I know what you did last PyCon')
        message = multipart.MIMEMultipart()
        message.attach(application.MIMEApplication(body))

        encoded = self._callFUT(message)

        self.assertTrue(encodestring(body) in encoded)
Пример #7
0
def enviar_datos(fichero, user):
    # Variables de envio de mail
    mailorigen = '*****@*****.**'
    maildestino = '*****@*****.**'

    # Contruimos partes del mensaje
    ahora = datetime.now()
    asunto = str(ahora) + '%' + str(user)
    nombrebase = 'attachment; filename = "bigdata_' + str(user) + '.sqlite3"'
    texto = 'Aqui va la base de datos! de ' + str(user) + ' de ' + str(ahora)

    # Establecemos conexion con el servidor smtp de gmail
    try:
        mailServer = smtplib.SMTP('smtp.gmx.es', 587)
    except:
        print(
            Fore.RED + Style.BRIGHT + 'ERROR INESPERADO! ' +
            'De momento, la base no ha podido ser enviada.\nAsegurate de estar conectado a internet y/o de no usar un proxy (habitual si te conectas en el trabajo).\nSi lo anterior es ok, por favor, avisa a uny11 en hattrick del problema.\nGracias de antemano y perdona las molestias'
        )
    mailServer.ehlo()
    mailServer.starttls()
    mailServer.ehlo()
    try:
        mailServer.login('*****@*****.**', 'bduny11Parma')
    except:
        print(
            Fore.RED + Style.BRIGHT + 'ERROR!' +
            'De momento, no tienes autorización para enviar la base al servidor. \n'
            + Fore.YELLOW + 'uny11 ' + Style.RESET_ALL +
            'acaba de recibir una notificación para autorizar tu usuario ' +
            Fore.YELLOW + Style.BRIGHT + str(user) + Style.RESET_ALL +
            '\nGracias por esperar su respuesta (en el foro de la federación BigData) para volver a intentar de nuevo más tarde\n'
        )

    # Construimos un mensaje Multipart
    mensaje = multipart.MIMEMultipart()
    mensaje['From'] = mailorigen
    mensaje['To'] = maildestino
    mensaje['Subject'] = asunto
    mensaje.attach(text.MIMEText(texto))
    # adjuntamos fichero
    file = open(fichero, 'rb')
    contenido = application.MIMEApplication(file.read())
    contenido.add_header('Content-Disposition', nombrebase)
    mensaje.attach(contenido)

    # Enviamos el correo, con los campos from y to.
    mailServer.sendmail(mailorigen, maildestino, mensaje.as_string())
    # Cierre de la conexion
    mailServer.close()
Пример #8
0
def get_message(email, file, cfg):
    msg = multipart.MIMEMultipart()
    msg['Subject'] = phrases["subject"]
    msg['From'] = cfg["login"]
    msg['To'] = email

    body = text.MIMEText(phrases["text"])
    msg.attach(body)

    fp = open(file, 'rb')
    pdf = application.MIMEApplication(fp.read(), _subtype="pdf")
    fp.close()
    pdf.add_header('Content-Disposition', 'attachment', filename=file)
    msg.attach(pdf)

    return msg
Пример #9
0
def _StowRs(study_path, jsonstr):
    # type: (str, str) -> None
    """Stores instance in Cloud Healthcare API using STOW-RS protocol.

  STOW-RS is one of the standard protocols specified by DICOMWeb protocol. It
  allows clients to store DICOM instances. In this case we will
  store the instance in in the Cloud Healthcare API specified by
  _HEALTHCARE_API_URL_PREFIX.

  Args:
    study_path: Path of DICOM study. This should be formatted as follows:
      projects/{PROJECT_ID}/locations/{LOCATION_ID}/datasets/{DATASET_ID}/
      dicomStores/{DICOM_STORE_ID}/dicomWeb/studies
    jsonstr: JSON represenation of DICOM instance(s) to store.

  Raises:
    RuntimeError: If failed to store instance.
  """
    stow_url = os.path.join(_HEALTHCARE_API_URL_PREFIX, study_path)
    http = httplib2.Http()
    http = _CREDENTIALS.authorize(http)
    application_type = 'dicom+json'

    boundary = str(uuid.uuid4())
    root = multipart.MIMEMultipart(subtype='related', boundary=boundary)
    # root should not write out its own headers
    setattr(root, '_write_headers', lambda self: None)
    part = application.MIMEApplication(jsonstr,
                                       application_type,
                                       _encoder=encoders.encode_noop)
    root.attach(part)

    boundary = root.get_boundary()
    content_type = ('multipart/related; type="application/%s"; boundary="%s"'
                    ) % (application_type, boundary)
    headers = {'content-type': content_type}

    resp, content = http.request(stow_url,
                                 method='POST',
                                 body=root.as_string(),
                                 headers=headers)
    if resp.status != 200:
        raise RuntimeError(
            'Failed to store DICOM instance in Healthcare API: (%s, %s)' %
            (resp.status, content))
Пример #10
0
def sendmail(body, filename=None, attachment=None):
    msg = multipart.MIMEMultipart()
    msg['Subject'] = 'Exportação ANP'
    msg['From'] = EMAIL_USER
    msg['To'] = EMAIL_TO

    msg.attach(text.MIMEText(body, 'plain'))

    if attachment:
        att = application.MIMEApplication(attachment.read(), _subtype="xlsx")
        att.add_header('Content-Disposition', 'attachment', filename=filename)
        msg.attach(att)

    sender = smtplib.SMTP('{}:{}'.format(EMAIL_HOST, EMAIL_PORT))
    sender.ehlo()
    sender.starttls()
    sender.login(EMAIL_USER, EMAIL_PASSWORD)
    sender.sendmail(EMAIL_USER, [EMAIL_TO], msg.as_string())
Пример #11
0
def dicomweb_store_instance(service_account_json, base_url, project_id,
                            cloud_region, dataset_id, dicom_store_id,
                            dcm_file):
    """Handles the POST requests specified in the DICOMweb standard."""
    url = '{}/projects/{}/locations/{}'.format(base_url, project_id,
                                               cloud_region)

    dicomweb_path = '{}/datasets/{}/dicomStores/{}/dicomWeb/studies'.format(
        url, dataset_id, dicom_store_id)

    # Make an authenticated API request
    session = get_session(service_account_json)

    with open(dcm_file) as dcm:
        dcm_content = dcm.read()

    # All requests to store an instance are multipart messages, as designated
    # by the multipart/related portion of the Content-Type. This means that
    # the request is made up of multiple sets of data that are combined after
    # the request completes. Each of these sets of data must be separated using
    # a boundary, as designated by the boundary portion of the Content-Type.
    multipart_body = multipart.MIMEMultipart(
        subtype='related', boundary=email.generator._make_boundary())
    part = application.MIMEApplication(dcm_content,
                                       'dicom',
                                       _encoder=encoders.encode_noop)
    multipart_body.attach(part)
    boundary = multipart_body.get_boundary()

    content_type = ('multipart/related; type="application/dicom"; ' +
                    'boundary="%s"') % boundary
    headers = {'Content-Type': content_type}

    try:
        response = session.post(dicomweb_path,
                                data=multipart_body.as_string(),
                                headers=headers)
        response.raise_for_status()
        print('Stored DICOM instance:')
        print(response.text)
        return response
    except HttpError as err:
        print(err)
        return ""
Пример #12
0
def send_mail(send_from=None,
              password=None,
              send_to=None,
              path_file=None,
              server=None):
    """This function is to send a notify email to Admin.
    :param send_from: Email of dispatcher.
    :param password: Password of dispatcher.
    :param send_to: Email of receiver.
    :param path_file: File attachment.
    :param server: Email server. If no input then gmail is a default server.
    Form server: ip_server:port_server
    :return:
    """
    # Set default options
    subject = "Report OpenStack status"
    text = "Dear Admin \n," \
           "I would like to send an email to report the status of Openstack"

    hostname, port = server.split(':')
    msg = multipart.MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = send_to
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach(tx.MIMEText(text))

    with open(path_file, "rb") as fil:
        part = application.MIMEApplication(fil.read(),
                                           Name=basename(path_file))
        part['Content-Disposition'] = 'attachment; filename="%s"' % basename(
            path_file)
        msg.attach(part)

    smtp = smtplib.SMTP(host=hostname, port=port)
    smtp.starttls()
    smtp.login(user=send_from, password=password)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()
Пример #13
0
def send_report(report):
    html_file = os.path.dirname(__file__)
    html_file = os.path.join(html_file, "mail.html")
    message = mime_multipart.MIMEMultipart('html')
    message["Subject"] = (pathlib.Path(report["vcs_root"]).name + ": " +
                          report["config_path"])
    message["From"] = sender
    message["To"] = recipients

    with open(html_file) as mail_file:
        message_str = mail_file.read()

        for key, val in report.items():
            message_str = message_str.replace("{" + key + "}", str(val))

        message_mime = mime_text.MIMEText(message_str, 'html')
        message.attach(message_mime)
        for f in attachments:
            if f is None or (not os.path.exists(f)):
                log.error("failed to send attachment: " + str(f))
                continue
            with open(f, "rb") as fil:
                part = mime_application.MIMEApplication(
                    fil.read(), Name=os.path.basename(f))
            # After the file is closed
            part['Content-Disposition'] = ('attachment; filename="%s"' %
                                           os.path.basename(f))
            message.attach(part)

    if login:
        try:
            server = smtplib.SMTP_SSL(host)
            server.ehlo()
            server.login(*login)
            server.send_message(message)
            server.quit()
        except:
            log.error("failed to send mail")
Пример #14
0
def format_message(To="",
                   From="",
                   Subject="",
                   Body="",
                   Date="",
                   Attachments=()):
    """creates a message to send with parameters all set no none"""
    base = multipart.MIMEMultipart()
    if To != "":
        base["To"] = to
    if From != "":
        base["From"] = fro
    if Subject != "":
        base["Subject"] = subject
    if Date != "":
        base["Date"] = Date
    if Body != "":
        base.attach(text.MIMEText(Body))
    for attach in Attachments:
        part = application.MIMEApplication(attach[1], Name=attach[0])
        part["Content-Disposition"] = "attachment; filename=\"%s\"" % attach[0]
        base.attach(part)
    return base.as_string()
Пример #15
0
def send_email(email_sender='me',
               email_to='',
               email_subject='',
               email_body_html='',
               email_cc='',
               email_bcc='',
               files=None):
    credentials = get_credentials()
    service = discovery.build(serviceName='gmail',
                              version='v1',
                              credentials=credentials)

    message = multipart.MIMEMultipart()
    message['to'] = email_to
    message['from'] = email_sender
    message['date'] = utils.formatdate(localtime=True)
    message['subject'] = email_subject
    message['cc'] = email_cc
    message['bcc'] = email_bcc
    message.attach(text.MIMEText(email_body_html, 'html'))

    for f in files or []:
        f = f.strip(' ')
        mimetype, encoding = mimetypes.guess_type(f)

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

        if main_type == 'text':
            with open(f, 'rb') as outfile:
                attachement = text.MIMEText(outfile.read(), _subtype=sub_type)
        elif main_type == 'image':
            with open(f, 'rb') as outfile:
                attachement = image.MIMEImage(outfile.read(),
                                              _subtype=sub_type)
        elif main_type == 'audio':
            with open(f, 'rb') as outfile:
                attachement = audio.MIMEAudio(outfile.read(),
                                              _subtype=sub_type)
        elif main_type == 'application' and sub_type == 'pdf':
            with open(f, 'rb') as outfile:
                attachement = application.MIMEApplication(outfile.read(),
                                                          _subtype=sub_type)
        else:
            attachement = base.MIMEBase(main_type, sub_type)
            with open(f, 'rb') as outfile:
                attachement.set_payload(outfile.read())

        encoders.encode_base64(attachement)
        attachement.add_header('Content-Disposition',
                               'attachment',
                               filename=os.path.basename(f))
        message.attach(attachement)

    msg_bytes = message.as_bytes()
    print(f"Message size: {format_size(len(msg_bytes))}")
    media_body = http.MediaIoBaseUpload(io.BytesIO(msg_bytes),
                                        mimetype='message/rfc822',
                                        resumable=True)
    body_metadata = {}
    print('Sending...')
    try:
        response = service.users().messages().send(
            userId='me', body=body_metadata, media_body=media_body).execute()
        print(response)
    except errors.HttpError as error:
        print('Error:\n{}'.format(error))
Пример #16
0
def get_details():
    parser = argparse.ArgumentParser(
        description='Sends email with attachment to multiple recipients.')
    parser.add_argument(
        'sender_list', help='Path to the text file containing list of senders')
    parser.add_argument('attach_path', help='Path to the attachment file')
    parser.add_argument('text_body',
                        help='Path to the text file containing email message')
    parser.add_argument(
        '-ex',
        '--exclude',
        metavar='old_file',
        help=
        'Compare new contact file with old and send the mail to new ones only')
    args = parser.parse_args()

    if args.exclude:
        if os.path.splitext(args.exclude)[1] == ".csv":
            with open(args.exclude, newline='') as old_csv_data:
                reader = csv.reader(old_csv_data)
                for row in reader:
                    if not row[1] == "First Name":
                        if row[1] and row[5] and row[29]:
                            OLD_LIST.append(row[5])
        else:
            raise Exception("Old sender's list should also be in .csv format")

    if os.path.splitext(args.sender_list)[1] == ".csv":
        with open(args.sender_list, newline='') as csv_data:
            reader = csv.reader(csv_data)
            for row in reader:
                if not row[1] == "First Name":
                    if OLD_LIST and row[5] in OLD_LIST:
                        print(
                            "Skipping {0} - {1}. Email was sent in the previous run."
                            .format(row[1], row[5]))
                        continue
                    elif "Recruit" in row[31] or "Talent" in row[31] and row[
                            1] and row[5] and row[29]:
                        SENDER_LIST['Name'].append(row[1].encode(
                            'ascii', 'ignore'))
                        SENDER_LIST['Email'].append(row[5].encode(
                            'ascii', 'ignore'))
                        SENDER_LIST['Company'].append(row[29].encode(
                            'ascii', 'ignore'))
        print()
    else:
        raise Exception("Sender's list should be in .csv format")

    if os.path.isfile(args.attach_path):
        attachment = args.attach_path
    else:
        raise FileExistsError('Attachment file does not exists')

    user = input("Enter your first name: ")
    gmail_user = input("Enter your email id: ")
    gmail_pwd = getpass.getpass("Enter your password: "******"Full-time opportunities at {}".format(
                    recipient_company)
                msg.attach(text.MIMEText(content))

                part = application.MIMEApplication(
                    open(attachment, 'rb').read())
                part.add_header(
                    'Content-Disposition', 'attachment; filename="{}"'.format(
                        os.path.basename(attachment)))
                msg.attach(part)

                try:
                    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
                    mailServer.ehlo()
                    mailServer.starttls()
                    mailServer.ehlo()
                    mailServer.login(gmail_user, gmail_pwd)
                    mailServer.sendmail(gmail_user, str(mail_to),
                                        msg.as_string())
                    # Should be mailServer.quit(), but that crashes...
                    mailServer.close()
                    print(
                        "Successfully sent the email to {}".format(recipient))

                except Exception as e:
                    print("Failed to send email to {}. Reason: {}".format(
                        recipient, str(e)))
                counter += 1

            if not SENDER_LIST.get('Name'):
                break
            time.sleep(180)
            counter = 0
    else:
        raise FileExistsError('Message file does not exists')
Пример #17
0
	def close(self):
		if self._log:
			ul4log = []
			jsonlog = []
			for (timestamp, tags, tasks, obj) in self._log:
				if isinstance(obj, BaseException):
					excclass = misc.format_class(obj)
					value = str(obj) or None
					tb = _formattraceback(obj)
					ul4log.append({"type": "exception", "timestamp": timestamp, "class": excclass, "value": value, "traceback": tb, "tasks": tasks})
					jsonlog.append({"type": "exception", "timestamp": timestamp.isoformat(), "class": excclass, "value": value, "traceback": tb, "tasks": [task.asjson() for task in tasks]})
				else:
					message = "\n".join(_formatlines(obj))
					ul4log.append({"type": "message", "timestamp": timestamp, "message": message, "tasks": tasks})
					jsonlog.append({"type": "message", "timestamp": timestamp.isoformat(), "message": message, "tasks": [task.asjson() for task in tasks]})

			jsondata = dict(
				projectname=self.job.projectname,
				jobname=self.job.jobname,
				identifier=self.job.identifier,
				log=jsonlog,
				countexceptions=self._countexceptions,
				countmessages=self._countmessages,
				host_name=misc.sysinfo.host_name,
				host_fqdn=misc.sysinfo.host_fqdn,
				host_ip=misc.sysinfo.host_ip,
				host_sysname=misc.sysinfo.host_sysname,
				host_nodename=misc.sysinfo.host_nodename,
				host_release=misc.sysinfo.host_release,
				host_version=misc.sysinfo.host_version,
				host_machine=misc.sysinfo.host_machine,
				user_name=misc.sysinfo.user_name,
				user_uid=misc.sysinfo.user_uid,
				user_gid=misc.sysinfo.user_gid,
				user_gecos=misc.sysinfo.user_gecos,
				user_dir=misc.sysinfo.user_dir,
				user_shell=misc.sysinfo.user_shell,
				python_executable=misc.sysinfo.python_executable,
				python_version=misc.sysinfo.python_version,
				pid=misc.sysinfo.pid,
				script_name=misc.sysinfo.script_name,
				short_script_name=misc.sysinfo.short_script_name,
				starttime=self.job.starttime.isoformat() if self.job.starttime else None,
				endtime=self.job.endtime.isoformat() if self.job.endtime else None,
				logfileurl=self.job.logfileurl,
			)
			variables = dict(
				job=self.job,
				sysinfo=misc.sysinfo,
				log=ul4log,
				countexceptions=self._countexceptions,
				countmessages=self._countmessages,
			)
			emailsubject = self.job._formatemailsubject.renders(**variables)
			emailbodytext = self.job._formatemailbodytext.renders(**variables)
			emailbodyhtml = self.job._formatemailbodyhtml.renders(**variables)

			textpart = text.MIMEText(emailbodytext)
			htmlpart = text.MIMEText(emailbodyhtml, _subtype="html")
			jsonpart = application.MIMEApplication(json.dumps(jsondata).encode("utf-8"), _subtype="json", _encoder=encoders.encode_base64)
			jsonpart.add_header('Content-Disposition', 'attachment', filename=f"{self.job.projectname}.{self.job.jobname}.json")

			msg = multipart.MIMEMultipart(
				_subparts=[
					multipart.MIMEMultipart(_subtype="alternative", _subparts=[textpart, htmlpart]),
					jsonpart,
				]
			)

			msg["To"] = self.job.toemail
			msg["From"] = self.job.fromemail
			msg["Subject"] = emailsubject
			try:
				server = smtplib.SMTP(self.job.smtphost, self.job.smtpport)
				if self.job.smtpuser and self.job.smtppassword:
					server.login(self.job.smtpuser, self.job.smtppassword)
				server.send_message(msg)
				server.quit()
				self.job.log.sisyphus.report(f"Sent email report to {self.job.toemail}")
			except smtplib.SMTPException as exc:
				self.job.log.sisyphus.report(exc)
Пример #18
0
def send_email(email_subject,
               email_body,
               email_sender='',
               email_to='',
               email_cc='',
               email_bcc='',
               files=None):

    # Pulling in the string value of the service key from the parameter
    with open(r'C:\Users\___.json') as f:
        service_account_info = json.loads(f.read())

    # Define which scopes we're trying to access
    SCOPES = ['https://www.googleapis.com/auth/gmail.send']

    # Setting up credentials using the gmail api
    credentials = service_account.Credentials.from_service_account_info(
        service_account_info, scopes=SCOPES)
    # This allows us to assign an alias account to the message so that the messages aren't coming from 'ServiceDriod-8328balh blah blah'
    delegated_credentials = credentials.with_subject(email_sender)
    # 'Building' the service instance using the credentials we've passed
    service = discovery.build(serviceName='gmail',
                              version='v1',
                              credentials=delegated_credentials)

    # Building out the email
    message = multipart.MIMEMultipart()
    message['to'] = email_to
    message['from'] = email_sender
    message['date'] = utils.formatdate(localtime=True)
    message['subject'] = email_subject
    message['cc'] = email_cc
    message['bcc'] = email_bcc
    message.attach(text.MIMEText(email_body, 'plain'))

    for f in files or []:
        f = f.strip(' ')
        mimetype, encoding = mimetypes.guess_type(f)

        # If the extension is not recognized it will return: (None, None)
        # If it's an .mp3, it will return: (audio/mp3, None) (None is for the encoding)
        # For an unrecognized extension we set mimetype to 'application/octet-stream' so it won't return None again.
        if mimetype is None or encoding is not None:
            mimetype = 'application/octet-stream'
        main_type, sub_type = mimetype.split('/', 1)

        # Creating the attachement:
        # This part is used to tell how the file should be read and stored (r, or rb, etc.)
        if main_type == 'text':
            print('text')
            with open(f, 'rb') as outfile:
                attachement = text.MIMEText(outfile.read(), _subtype=sub_type)
        elif main_type == 'image':
            print('image')
            with open(f, 'rb') as outfile:
                attachement = image.MIMEImage(outfile.read(),
                                              _subtype=sub_type)
        elif main_type == 'audio':
            print('audio')
            with open(f, 'rb') as outfile:
                attachement = audio.MIMEAudio(outfile.read(),
                                              _subtype=sub_type)
        elif main_type == 'application' and sub_type == 'pdf':
            with open(f, 'rb') as outfile:
                attachement = application.MIMEApplication(outfile.read(),
                                                          _subtype=sub_type)
        else:
            attachement = base.MIMEBase(main_type, sub_type)
            with open(f, 'rb') as outfile:
                attachement.set_payload(outfile.read())

        encoders.encode_base64(attachement)
        attachement.add_header('Content-Disposition',
                               'attachment',
                               filename=os.path.basename(f))
        message.attach(attachement)

    media_body = http.MediaIoBaseUpload(io.BytesIO(message.as_bytes()),
                                        mimetype='message/rfc822',
                                        resumable=True)
    body_metadata = {}  # no thread, no labels in this example

    try:
        print('Uploading file...')
        response = service.users().messages().send(
            userId='me', body=body_metadata, media_body=media_body).execute()
        print(response)
    except errors.HttpError as error:
        print('An error occurred when sending the email:\n{}'.format(error))