Example #1
2
def send(server, from_addr, to_addrs, subject, msg_text, msg_html,
        cc_addrs = None, bcc_addrs = None):
    """ Sends an email to a set of recipients by using a SMTP sever

        from_addr -- The email address of the sender
        to_addsr -- A list of destination email addresses
        subject -- Subject of the email
        msg_text -- The email message in plain text format
        msg_html -- THe email message in HTML format
        cc_addrs -- A list of CC destination email addresses
        bcc_addrs -- A list of BCC destination email addresses
    """

    # Create message container - the correct MIME type is multipart/alternative.
    msg = MIMEMultipart('alternative')
    msg['Subject'] = subject
    msg['From'] = from_addr
    msg['To'] = ','.join(to_addrs)
    if (cc_addrs and len(cc_addrs) > 0):
        msg['Cc'] = ','.join(cc_addrs)
    if (bcc_addrs and len(bcc_addrs) > 0):
        msg['Bcc'] = ','.join(bcc_addrs)

    # Record the MIME types of both parts - text/plain and text/html.
    part1 = MIMEText(unicode(msg_text).encode('utf-8'), 'plain')
    part2 = MIMEText(unicode(msg_html).encode('utf-8'), 'html')

    # Attach parts into message container.
    # According to RFC 2046, the last part of a multipart message, in this case
    # the HTML message, is best and preferred.
    msg.attach(part1)
    msg.attach(part2)
 
    server.sendmail(from_addr, to_addrs, msg.as_string())
Example #2
0
    def send_one_group(mail_list, account, mail_sub, mail_body, msg_append_list):
        err = ERROR_SUCCESS
        err_info = ""
        fail_mail = []  # 部分发送失败的邮件

        me = account.sender_name + "<"+account.user+">"

        msg = MIMEMultipart()
        msg['Subject'] = mail_sub
        msg['From'] = me
        msg['BCC'] = ";".join(mail_list)

        msg_text = MIMEText(mail_body, 'html', MailProc.ENCODE)
        msg.attach(msg_text)

        for each_append in msg_append_list:
            msg.attach(each_append)

        logging("Start to send a group.")
        s = smtplib.SMTP()
        try:
            s.connect(account.host)
        except Exception, e:
            err = ERROR_CONNECT_FAILED
            err_info = u"连接{}失败,请检查网络是否通畅\n错误信息: {}".format(account.host, e)
            return err, err_info, fail_mail
Example #3
0
    def send(self):
        msg = MIMEMultipart()   
        msg['From'] = self.sender  
        msg['To'] = ';'.join(self.to_list)
        msg['Subject'] = self.subject   
        
        result_list = self.body        
        text = "Single user try " + ("succeed.\n" if result_list[0] else "failed.\n")
        for sub_list in result_list[1:]:
            text += ("  [ PASS ] " if sub_list[1] else "  [FAILED] ") + "Script: " + sub_list[0] + "\n"
            if not sub_list[1]:
                for item in sub_list[2:]:
                    if item[2]:
                        text += "    Transaction: \"" + item[0] + "\" failed.\n"
        
        msg.attach(MIMEText(text,_charset='utf-8'))

        logger.info("E-mail - Server: " + self.server)        
        logger.info("E-mail - From: " + msg['From'])
        logger.info("E-mail - To: " + msg['To'])
        logger.info("E-mail - Body: " + text)
        
        smtp = smtplib.SMTP()   
        smtp.connect(self.server)   
        smtp.sendmail(msg['From'], self.to_list, msg.as_string())   
        smtp.quit()
 def setUp(self):
     
     #set up the image for the message
     ePic = 'v:/workspace/HandlingEmail_Homework/src/python-logo.png'
     att = open(ePic, 'rb')
     img = MIMEImage(att.read())
     att.close()
     img.add_header('Content-Disposition', 'attachment', filename=os.path.basename(ePic))
     
     #set up the message body
     msgText = MIMEText("This is a test string", 'plain')
     
     #build the message
     msg = MIMEMultipart()
     msg['To'] = '*****@*****.**'
     msg['From'] = '*****@*****.**'
     msg['Subject'] = 'Test Email'
     msg.attach(msgText)
     msg.attach(img)
     self.Mmsg = msg
     
     #create a set for comparison
     self.attachmentSet = {msgText.as_string(), img.as_string()}
     
     #engages the function
     attachments = [ePic]
     mailObj = emailReturn('*****@*****.**', 'This is a test string', attachments)
     self.mailTest = mailObj
Example #5
0
def send_email(to, subject, body):
    # create email
    msg = MIMEMultipart()
    msg['From'] = qiita_config.smtp_email
    msg['To'] = to
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))

    # connect to smtp server, using ssl if needed
    if qiita_config.smtp_ssl:
        smtp = SMTP_SSL()
    else:
        smtp = SMTP()
    smtp.set_debuglevel(False)
    smtp.connect(qiita_config.smtp_host, qiita_config.smtp_port)
    # try tls, if not available on server just ignore error
    try:
        smtp.starttls()
    except SMTPException:
        pass
    smtp.ehlo_or_helo_if_needed()

    if qiita_config.smtp_user:
        smtp.login(qiita_config.smtp_user, qiita_config.smtp_password)

    # send email
    try:
        smtp.sendmail(qiita_config.smtp_email, to, msg.as_string())
    except Exception:
        raise RuntimeError("Can't send email!")
    finally:
        smtp.close()
Example #6
0
    def test_mixed_cloud_config(self):
        blob_cc = """
#cloud-config
a: b
c: d
"""
        message_cc = MIMEBase("text", "cloud-config")
        message_cc.set_payload(blob_cc)

        blob_jp = """
#cloud-config-jsonp
[
     { "op": "replace", "path": "/a", "value": "c" },
     { "op": "remove", "path": "/c" }
]
"""

        message_jp = MIMEBase("text", "cloud-config-jsonp")
        message_jp.set_payload(blob_jp)

        message = MIMEMultipart()
        message.attach(message_cc)
        message.attach(message_jp)

        ci = stages.Init()
        ci.datasource = FakeDataSource(str(message))
        new_root = self.makeDir()
        self.patchUtils(new_root)
        self.patchOS(new_root)
        ci.fetch()
        ci.consume_userdata()
        cc_contents = util.load_file(ci.paths.get_ipath("cloud_config"))
        cc = util.load_yaml(cc_contents)
        self.assertEquals(1, len(cc))
        self.assertEquals("c", cc["a"])
Example #7
0
    def smtpSendWithFile(self, toList, sub, att):
        msg = MIMEMultipart()
        me = 'Ming<{0}@{1}>'.format(self.mail_user,self.mail_postfix)
        msg['Subject'] = Header(sub,'utf-8')
        msg['From'] = me
        msg['To'] = ','.join(toList)
        #with open(att,'rb') as fp:
        #    content = MIMEBase('application', 'octet-stream')
        #    content.set_payload(fp.read())
        with open(att,'rb') as fp:
            content = MIMEText(fp.read(), _subtype = 'plain', _charset = 'utf-8')
        #encoders.encode_base64(content)
        fileName = '{0}_{1}'.format(sub, os.path.basename(att))
        content.add_header('Content-Disposition', 'attachment', filename = fileName)
        msg.attach(content)
        composed = msg.as_string()
        try:
          s = smtplib.SMTP()
          s.connect(self.mailHost)
          s.login(self.mail_user, self.mail_pwd)
          s.sendmail(me, toList, composed)
          s.close()
          return True
        except Exception as e:
          print(str(e))
          return False

#monitor = WinMonitorClass()
#content = "This is only a test mail sent by Python. Click following link to go to <a href='http://www.baidu.com'>百度</a>"
##monitor.imapHelper()
#mailtoList = [r'*****@*****.**', r'*****@*****.**',r'*****@*****.**']
#if monitor.smtpSend(mailtoList, "Hello SMTP!", content):
#    print("Send Successfully...")
#else:
#    print("Send Mail Failed!!!")
Example #8
0
def send_email(subject=None, message=None, from_addr=None, to_addr=None):
    '''
    Send am email via SMTP server.
    This will not prompt for login if you are alread on the internal network.
    '''
    import os
    import getpass
    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart

    users_email=getpass.getuser()+'@stsci.edu'

    if not subject:
        subject='Message from %s'%(__file__)
    if not message:
        message='You forgot to put a message into me'
    if not from_addr:
        from_addr=users_email
    if not to_addr:
        to_addr=users_email

    svr_addr='smtp.stsci.edu'
    msg = MIMEMultipart()
    msg['Subject']=subject
    msg['From']=from_addr
    msg['To']=to_addr
    msg.attach(MIMEText(message))
    s = smtplib.SMTP(svr_addr)
    s.sendmail(from_addr, to_addr, msg.as_string())
    s.quit()
    print('\nEmail sent to %s \n' %(from_addr))
Example #9
0
def send_email(request):

    ''' View to send reciept email to a user when they check out '''

    ''' TODO: Dead code for now, integrate with template output in future '''

    if request.method == 'POST':
        auction_user = AuctionUser.objects.get(id=user_id)
        auction = Auction.objects.get(id=auction_id)

        msg = MIMEMultipart()
        msg['Subject'] = "Reciept from {}".format(str(auction.name))
        msg['From'] = settings.DJAUCTION_SMTP_USER
        msg['To'] = auction_user.email
        msg_text = ''
        mime_text = MIMEText(msg_text, 'plain')
        msg.attach(mime_text)

        server = smtplib.SMTP(settings.DJAUCTION_SMTP_SERVER, settings.DJAUCTION_SMTP_PORT)
        server.ehlo()
        server.starttls()
        server.ehlo()
        server.login(settings.DJAUCTION_SMTP_USER, settings.DJAUCTION_SMTP_PASS)
        server.sendmail(settings.DJAUCTION_SMTP_USER, auction_user.email, msg.as_string())
        server.close()
        return HttpResponseRedirect(reverse(view_user, args=(auction_user.id,auction.id)))
Example #10
0
def send_email(gmail_user, gmail_pwd, FROM, TO, SUBJECT, TEXT):
    """Send an HTML email with a Gmail account"""
    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText

    """START GMAIL settings"""
    SERVER = "smtp.gmail.com"
    PORT = 587  # Google says 465 works too

    """START Message settings"""
    message = MIMEMultipart("alternative")
    message["Subject"] = SUBJECT
    message["From"] = FROM
    message["To"] = ", ".join(TO)
    html = "<html><head></head><body>" + TEXT + "</body></html>"  # We add here HTML wrapping tags
    part = MIMEText(html, "html")
    message.attach(part)

    try:
        server = smtplib.SMTP(SERVER, PORT)
        server.ehlo()
        server.starttls()
        server.login(gmail_user, gmail_pwd)
        server.sendmail(FROM, TO, message.as_string())
        server.close()
        # At this point, the email has been sent successfully!
    except:
        raise
Example #11
0
    def send(self):
        msg = MIMEMultipart()   
        msg['From'] = self.sender  
        msg['To'] = ';'.join(self.to_list)
        msg['Cc'] = ';'.join(self.cc_list)
        msg['Bcc'] = ';'.join(self.bcc_list)
        msg['Subject'] = self.subject   
        msg.attach(MIMEText(self.body,_charset='utf-8'))

        self.l.log("E-mail - Server: " + self.server)        
        self.l.log("E-mail - From: " + msg['From'])
        self.l.log("E-mail - To: " + msg['To'])
        self.l.log("E-mail - Cc: " + msg['Cc'])
        self.l.log("E-mail - Bcc: " + msg['Bcc'])
        self.l.log("E-mail - Subject: " + msg['Subject'])
        self.l.log("E-mail - Body: " + self.body)
        
        try:
            smtp = smtplib.SMTP()   
            smtp.connect(self.server)   
            address = [i for f in ('To', 'Cc', 'Bcc') if msg[f] for i in msg[f].split(',')]
            smtp.sendmail(msg['From'], address, msg.as_string())   
            smtp.quit()
            self.l.log('Email send successfully.')
        except Exception,e:
            self.l.log('Error: %s' % e)
Example #12
0
    def attach(self, payload):
        """
        Add the C{payload} to the current payload list.

        Also prevent from adding payloads with wrong Content-Type and from
        exceeding a maximum of 2 payloads.

        :param payload: The payload to be attached.
        :type payload: email.message.Message
        """
        # first payload's content type must be equal to the protocol parameter
        # given on object creation
        if len(self._payload) == 0:
            if payload.get_content_type() != self.get_param('protocol'):
                raise errors.MultipartConversionError(
                    'Wrong content type.')
        # second payload is always application/octet-stream
        if len(self._payload) == 1:
            if payload.get_content_type() != 'application/octet-stream':
                raise errors.MultipartConversionError(
                    'Wrong content type %s.' % payload.get_content_type)
        # prevent from adding more payloads
        if len(self._payload) == 2:
            raise errors.MultipartConversionError(
                'Cannot have more than two subparts.')
        MIMEMultipart.attach(self, payload)
Example #13
0
  def test_get_activities_extra_fetches_fail(self):
    """Sometimes the extras fetches return errors. Ignore that."""
    self.init()

    batch = MIMEMultipart()
    for i in range(3):
      msg = Message()
      msg.set_payload('HTTP/1.1 500 Foo Bar\n\r\n\r\n')
      msg['Content-ID'] = '<response-abc+%d>' % (i + 1)
      batch.attach(msg)

    # as_string() must be called before get_boundary() to generate the
    # boundaries between parts, but can't be called again, so we capture the
    # result.
    batch_str = batch.as_string()

    self.auth_entity.http = lambda: http.HttpMockSequence(
      [({'status': '200'}, json.dumps({'items': [ACTIVITY_GP_EXTRAS]})),
       ({'status': '200',
         'content-type': 'multipart/mixed; boundary="%s"' % batch.get_boundary()},
        batch_str),
       ])

    cache = util.CacheDict()
    self.assert_equals([ACTIVITY_AS], self.googleplus.get_activities(
        fetch_replies=True, fetch_likes=True, fetch_shares=True, cache=cache))
    for prefix in 'AGC ', 'AGL ', 'AGS ':
      self.assertNotIn(prefix + '001', cache)
Example #14
0
def sendEmail(e_from,e_to,e_host,e_passwd,e_sub="It's a test email.",e_content="test",cc_to=None,attachFile=None):
    msg = MIMEMultipart() 
    EmailContent = MIMEText(e_content,_subtype='html',_charset='utf-8')
    msg['Subject'] = "%s " % e_sub
    msg['From'] = e_from
    if e_to.find(',') == -1:
        msg['To'] = e_to
    else: 
        e_to = e_to.split(',')
        msg['To'] = ';'.join(e_to)  
    if cc_to:
        if cc_to.find(',') == -1:
            msg['Cc'] = cc_to
        else: 
            cc_to= cc_to.split(',')
            msg['Cc'] = ';'.join(cc_to)       
    msg['date'] = time.strftime('%Y %H:%M:%S %z')
    try:
        if attachFile:
            EmailContent = MIMEApplication(open(attachFile,'rb').read()) 
            EmailContent["Content-Type"] = 'application/octet-stream'
            fileName = os.path.basename(attachFile)
            EmailContent["Content-Disposition"] = 'attachment; filename="%s"' % fileName
        msg.attach(EmailContent)
        smtp=smtplib.SMTP()
        smtp.connect(e_host)
        smtp.login(e_from,e_passwd)
        smtp.sendmail(e_from,e_to,msg.as_string())
        smtp.quit()
    except Exception , e:
        print e
Example #15
0
def send_mail(body):
    import smtplib

    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText

    # me == my email address
    # you == recipient's email address
    me = "*****@*****.**"
    you = "*****@*****.**"

    # Create message container - the correct MIME type is multipart/alternative.
    msg = MIMEMultipart('alternative')
    msg['Subject'] = "You solved it!"
    msg['From'] = me
    msg['To'] = you

    # Record the MIME types of both parts - text/plain and text/html.
    email_text = MIMEText(body.decode(), 'html')

    # Attach parts into message container.
    msg.attach(email_text)

    # Send the message via local SMTP server.
    s = smtplib.SMTP('smtp.googlemail.com')
    s.starttls()
    s.login("*****@*****.**", "ValentinTagsCommit")
    # sendmail function takes 3 arguments: sender's address, recipient's address
    # and message to send - here it is sent as one string.
    s.sendmail(me, you, msg.as_string())
    s.quit()
Example #16
0
    def _send_alerts_if_any(self, alerts_to_send_map):
        """Evaluate if there are news to send. If that is the case, send the alerts.
        This version only supports lists grouped by email."""
        for email_to_string, alert_event_list in alerts_to_send_map.iteritems():
            if not self._is_something_to_report(alert_event_list):
                continue
            html_version_main = self._html_version_main()
            html_version_items = self._html_version_items(alert_event_list)
            html_version = html_version_main.format(html_version_items=html_version_items,
                                                    # TODO Externalize variables
                                                    date=datetime.datetime.now().strftime("%B %d, %Y"),
                                                    time=datetime.datetime.now().strftime("%I:%M %p"),
                                                    message_signature=hashlib.sha256(html_version_main + html_version_items + datetime.datetime.now().strftime("%B %d, %Y - %I:%M %p")).hexdigest(),
                                                    companyName=""
                                                    )
            # text_version = bs.get_text()

            # create email
            email = MIMEMultipart('alternative')
            # TODO calculate this value.
            email['Subject'] = "monitoring alert"
            email['From'] = self.email_from
            # email_to = email_to_string.split(',')
            email['To'] = email_to_string
            # part_text = MIMEText(text_version, 'plain', 'utf-8')
            # email.attach(part_text)
            part_html = MIMEText(html_version, 'html', 'utf-8')
            email.attach(part_html)

            self._send_email(email, email_to_string)
Example #17
0
 def _createMessage(self, subject):
   msg = MIMEMultipart()
   msg['Subject'] = subject
   msg['From'] = self.user
   msg['To'] = ",".join(self.recipients)
   msg.preample = 'Your mail attacment follows'
   return msg;
Example #18
0
    def send_email(cls, to, frm,
                   from_password,
                   subject='Motion detected!',
                   body=None,
                   attachment=None):
        '''Send email using GMail'''
        # email settings
        toaddr = to
        fromaddr = frm
        msg = MIMEMultipart()
        msg['To'] = toaddr
        msg['From'] = fromaddr
        msg['Subject'] = subject

        if body:
            msg.attach(MIMEText(body, 'plain'))

        if attachment:
            with open(attachment['file_name'], 'rb') as pic:
                attachment = MIMEImage(pic.read())
            msg.attach(attachment)

        server = smtplib.SMTP('smtp.gmail.com:587')
        server.starttls()
        server.login(fromaddr, from_password)
        server.send_message(msg, fromaddr, toaddr)
        server.quit()
Example #19
0
def send_report_after_ran_test():
    """根据 config 中的配置信息,在完成测试后通过邮件方式发送 HTML 格式报告给相关人
    Args: None.
    return: None.
    raise: None.
    """
    msg = MIMEMultipart()
    msg['subject'] = u"软件测试报告"
    msg['from'] = config.email_sender
    msg['to'] = config.email_reciver

    url = "http://" + config.report_server_name + ":" + config.report_server_port + "/report/" \
        + os.path.split(config.report_dir)[1] + '/summary_report.html'
    print_debug_info("the report's url is: " + url)

    report_content = MIMEText(urllib2.urlopen(url).read().decode('utf-8'), 'html')
    msg.attach(report_content)
    print_debug_info("report attached.")

    try:
        smtp = SMTP()
        smtp.connect(config.smtp_server_name, config.smtp_server_port)
        smtp.login(config.smtp_username, config.smtp_password)
        smtp.sendmail(config.email_sender, config.email_reciver, \
            msg.as_string())
        print_debug_info("report has already sent.")
        smtp.quit()
    except Exception, e:
        raise e
Example #20
0
    def new_student(self, student):
        """Compose an email for the event that a new student is added to
        the course"""
        text = self.get_text('message_new_student.rst')

        # Variables for the email
        recipient = student.email
        email_var = {}
        email_var['year'] = datetime.now().year
        email_var['name'] = student.name.split(' ')[0]
        email_var['course'] = student.course
        email_var['university'] = student.university
        email_var['repo_name'] = student.repo_name
        email_var['repo_adress'] = '[email protected]:/%s/%s.git' % \
                                        (student.org, student.repo_name)

        # Compose message
        text = self.get_text('message_new_student.rst')
        text = text % email_var
        text = self.rst_to_html(text).encode('utf-8') # ae, o, aa support
   
        # Compose email       
        msg = MIMEMultipart()
        msg['Subject']  = 'New repository'
        msg['To'] = recipient
        msg['From'] = self.server_connection.email
        body_text = MIMEText(text, 'html', 'utf-8')
        msg.attach(body_text)

        self.send(msg, recipient)
Example #21
0
def main():

    print("\ncompose e-mail and send\n")
    message = MIMEMultipart("alternative")
    message["Subject"] = get_input("subject: ")
    message["From"]    = get_input("from (e.g. thecolonel@localhost): ")
    message["To"]      = get_input("to: ")
    text               = get_input("message: ")

    part1 = MIMEText(text, "plain")

    message.attach(part1)

    get_input("\nPress Enter to send.\n")

    try:
        server = smtplib.SMTP("localhost")
        server.sendmail(
            message["From"],
            message["To"],
            message.as_string()
        )
        server.quit()
    except smtplib.SMTPException:
       print("e-mail send error")
Example #22
0
    def _multipart(self):
        """The email has attachments"""

        msg = MIMEMultipart('related')

        if self.Html:
            outer = MIMEMultipart('alternative')
            
            part1 = MIMEText(self.Body, 'plain', self.charset)
            part1.add_header('Content-Disposition', 'inline')

            part2 = MIMEText(self.Html, 'html', self.charset)
            part2.add_header('Content-Disposition', 'inline')

            outer.attach(part1)
            outer.attach(part2)
            msg.attach(outer)
        else:
            msg.attach(MIMEText(self.Body, 'plain', self.charset))

        self._set_info(msg)
        msg.preamble = self.Subject

        for filename, cid in self.attachments:
            self._add_attachment(msg, filename, cid)

        return msg.as_string()
Example #23
0
def send_email(subject='PycQED needs your attention!',
               body = '', email=None):
    # Import smtplib for the actual sending function
    import smtplib
    # Here are the email package modules we'll need
    from email.mime.image import MIMEImage
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText

    if email is None:
        email = qt.config['e-mail']

    # Create the container (outer) email message.
    msg = MIMEMultipart()
    msg['Subject'] = subject
    family = '*****@*****.**'
    msg['From'] = '*****@*****.**'
    msg['To'] = email
    msg.attach(MIMEText(body, 'plain'))


    # Send the email via our own SMTP server.
    s = smtplib.SMTP_SSL('smtp.gmail.com')
    s.login('*****@*****.**', 'DiCarloLab')
    s.sendmail(email, family, msg.as_string())
    s.quit()
Example #24
0
def send_email(to, subject, html_content, files=None, dryrun=False):
    """
    Send an email with html content

    >>> send_email('*****@*****.**', 'foo', '<b>Foo</b> bar', ['/dev/null'], dryrun=True)
    """
    SMTP_MAIL_FROM = configuration.get('smtp', 'SMTP_MAIL_FROM')

    if isinstance(to, basestring):
        if ',' in to:
            to = to.split(',')
        elif ';' in to:
            to = to.split(';')
        else:
            to = [to]

    msg = MIMEMultipart('alternative')
    msg['Subject'] = subject
    msg['From'] = SMTP_MAIL_FROM
    msg['To'] = ", ".join(to)
    mime_text = MIMEText(html_content, 'html')
    msg.attach(mime_text)

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

    send_MIME_email(SMTP_MAIL_FROM, to, msg, dryrun)
Example #25
0
def auto_email_alert():
    file_list = ["FastTrack_", "FastTrack-Edit_",
                 "JobOffer_"]
    #FROM = "*****@*****.**"
    FROM = "Data [email protected]"
    TO = ["*****@*****.**"]

    attachment = 'C:\\users\\ryanm\\desktop\\JL.jpg'

    msg = MIMEMultipart()
    msg['Subject'] = "Conversion Level Alert"
    msg['To'] = '*****@*****.**'

    body = ""
    main_message = "The weekly conversion level tests have finished. You can find them at %s, %s, and %s" % \
                   (os.path.normpath(alert_path_alt + file_list[0] + today + "_Conversion_Alert_Comparison.csv"),
                    os.path.normpath(alert_path_alt + file_list[1] + today + "_Conversion_Alert_Comparison.csv"),
                    os.path.normpath(alert_path_alt + file_list[2] + today + "_Conversion_Alert_Comparison.csv"))

    msgText = MIMEText('<b>%s</b><br><img src="cid:C:\\users\\ryanm\\desktop\\JL.jpg"><br>' % body, 'html')

    msg.attach(MIMEText(main_message))
    #msg.attach(msgText)

    server = smtplib.SMTP('owa.payscale.com')
    server.sendmail(FROM, TO, msg.as_string())
    server.quit()
Example #26
0
 def _msg(self, recipient_email, subject):
     msg = MIMEMultipart('alternative')
     msg['Subject'] = subject
     msg['From'] = "%s <%s>" % (self.user_real_name, self.reply_to)
     msg['To'] = recipient_email
     msg.add_header('reply-to', self.reply_to)
     return msg
Example #27
0
 def send(self, to, subject, msg):
     msg_mime = MIMEMultipart('alternative')
     msg_mime.attach(MIMEText(msg, 'html'))
     msg_mime['Subject'] = subject
     msg_mime['From'] = self.from_addr
     msg_mime['To'] = to
     self.server.sendmail(self.from_addr, to, msg_mime.as_string())
Example #28
0
class Mailer(Server):
    """
    Mailer class to process messages
    """

    def __init__(self, api_key, smtp_port=None):
        """
        Keyword Arguments:
            api_key {str} -- SendGrid Api Key
            smtp_port {str} -- Sendgrid support different smtp ports (optional)
        """

        self.api_key = api_key
        self.api_user = '******'
        self.smtp_port = smtp_port
        self.smtp_host = 'smtp.sendgrid.net'


    def headers(self, sender, recipients, subject):
        """Setting mail configuration

        Keyword Arguments:
            sender {str} -- Email who sends the message (default: {''})
            recipients {str} or {list} -- Recipient Emails (default: {None})
            subject {str} -- Subject of the message (default: {''})

        Raises:
            Exception -- Recipients information has not a valid type
        """

        self.__initialize()

        self._session_message['From'] = sender
        self._session_message['Subject'] = subject

        if isinstance(recipients, list):
            self._session_message['To'] = ", ".join(recipients)
        elif isinstance(recipients, str):
            self._session_message['To'] = recipients
        else:
            raise SGSError('Recipients information has not a valid value.')


    def content(self, content, content_type="plain", is_attach=False):
        """[summary]

        Keyword Arguments:
            content {str} -- Plain text, HTML content or File path
            content_type {str} -- plain or html (default: {plain})
        """

        if is_attach:
            self.__add_attachment(content)

        else:
            self.__add_content(content, content_type)


    def __initialize(self):
        self._session_message = MIMEMultipart()


    def __add_attachment(self, path_attach=""):
        """Add an attachment to the message

        Keyword Arguments:
            path_attach {str} -- File path (default: {''})

        Raises:
            Exception -- Path is not a valid file type
        """

        if not os.path.isfile(path_attach):
            raise SGSError('Path is not a valid file type.')


        def guess_mime(path_attach):
            """
            Guess file mimetype
            """
            ctype, encoding = mimetypes.guess_type(path_attach)
            if ctype is None or encoding is not None:
                ctype = 'application/octet-stream'

            main_type, sub_type = ctype.split('/', 1)
            return main_type, sub_type

        def open_attach(path_attach):
            """
            Open and read file
            """
            with open(path_attach, 'rb') as file_name:
                return file_name.read()
            return ""

        def get_filename(path_attach):
            file_path = open(path_attach)
            return os.path.basename(file_path.name)

        # Guess Mime
        main_type, sub_type = guess_mime(path_attach)
        if main_type == 'text':
            content = ""
            with open(path_attach) as file_name:
                content = file_name.read()

            attach = MIMEText(content, _subtype=sub_type)
        else:
            # Object
            content = open_attach(path_attach)
            if main_type == 'image':
                attach = MIMEImage(content, _subtype=sub_type)
            elif main_type == 'audio':
                attach = MIMEAudio(content, _subtype=sub_type)
            else:
                attach = MIMEBase(main_type, sub_type)
                attach.set_payload(content)

        # Set the filename parameter
        attach.add_header(
            'Content-Disposition',
            'attachment',
            filename=get_filename(path_attach)
        )

        self._session_message.attach(attach)


    def __add_content(self, text="", content_type="plain"):
        """[summary]

        Keyword Arguments:
            text {str} -- Plain text or HTML content (default: {""})
            content_type {str} -- html or plain (default: {plain})
        """

        self._session_message.attach(MIMEText(text, content_type))
Example #29
0
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

fromaddr = "*****@*****.**"
toaddr = "*****@*****.**"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Alerta!"

bodyt = open("alert.txt", 'r', encoding='utf-8')
body = MIMEText(bodyt.read(), 'html')
msg.attach(body)

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "!C3S@R!S")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
bodyt.close()
server.quit()
Example #30
0
class Email:
    def __init__(
        self,
        server,
        sender,
        password,
        receiver,
        title,
        message=None,
        path=None,
    ):
        """
        初始化邮件
        :param server: smtp服务器
        :param sender: 发件人
        :param password: 发件人密码
        :param receiver: 收件人
        :param title: 邮件标题
        :param message: 邮件正文,非必填
        :param path:附件路径,可传入list,非必填
        """
        self.server = server
        self.sender = sender
        self.password = password
        self.receiver = receiver
        self.title = title
        self.msg = MIMEMultipart('related')
        self.message = message
        self.files = path

    def _attach_file(self, att_file):
        """
        将单个文件添加到附件中
        :param att_file:
        :return:
        """
        att = MIMEText(open(att_file, 'rb').read(), 'plain', 'utf-8')
        att["Content-Type"] = 'application/octet-stream'
        file_name = re.split(r'[\\|/]', att_file)
        att["Content-Disposition"] = 'attachment;filename=%s' % file_name[-1]
        self.msg.attach(att)

    def send(self):
        self.msg['Subject'] = self.title
        self.msg['From'] = self.sender
        self.msg['To'] = self.receiver
        # self.msg['cc'] = self.cc

        # 邮件正文
        if self.message:
            self.msg.attach(MIMEText(self.message))

        # 添加附件(list / str)
        if self.files:
            if isinstance(self.files, list):
                for f in self.files:
                    self._attach_file(f)
            elif isinstance(self.files, str):
                self._attach_file(self.files)

        # 发送
        try:
            smtp_server = smtplib.SMTP(self.server)
        except Exception as e:
            logger1.exception('发送邮件失败,无法连接到SMTP服务器。%s', e)
        else:
            try:
                smtp_server.login(self.sender, self.password)
            except smtplib.SMTPAuthenticationError as e:
                logger1.exception('用户名密码校验失败。%s', e)
            else:
                smtp_server.sendmail(self.sender, self.receiver.split(';'),
                                     self.msg.as_string())
            finally:
                smtp_server.quit()
                logger1.info('发送邮件{0}成功! 收件人:{1}'.format(
                    self.title, self.receiver))
        to_addresses.append(args.to_address)
    elif args.to_address_filename is not None:
        try:
            with open(args.to_address_filename, "r") as to_address_file:
                to_addresses = to_address_file.readlines()
        except IOError as e:
            logging.error("Could not locate file %s", args.to_address_filename)
            raise e
    else:
        logging.error("Could not load input file names")
        exit(1)

    try:
        output_info("Connecting to SMTP server at " + args.smtp_server + ":" + str(args.smtp_port))
        server = smtplib.SMTP(args.smtp_server, args.smtp_port)
        msg = MIMEMultipart("alternative")
        msg.set_charset("utf-8")

        if args.from_name is not None:
            output_info("Setting From header to: " + args.from_name + "<" + args.from_address + ">")
            msg["From"] = args.from_name + "<" + args.from_address + ">"
        else:
            output_info("Setting From header to: " + args.from_address)
            msg["From"] = args.from_address

        if args.subject is not None:
            output_info("Setting Subject header to: " + args.subject)
            msg["Subject"] = args.subject

        if args.important:
            msg['X-Priority'] = '2'
Example #32
0
def send_mail(host, pdf_path):
	'''
	发送邮件报告
	'''
	#主题邮件内容
	contents = """
		<!DOCTYPE html>
		<html lang="en">
		<head>
		    <meta charset="UTF-8">
		    <title>未来安全局</title>
		    <style>
		        .smart-green {
		            margin-left: auto;
		            margin-right: auto;
		            max-width: 500px;
		            background: #F8F8F8;
		            padding: 30px 30px 20px 30px;
		            font: 12px Arial, Helvetica, sans-serif;
		            color: #666;
		            border-radius: 5px;
		            -webkit-border-radius: 5px;
		            -moz-border-radius: 5px;
		        }

		        .smart-green h1 {
		            font: 24px "Trebuchet MS", Arial, Helvetica, sans-serif;
		            padding: 20px 0px 20px 40px;
		            display: block;
		            margin: -30px -30px 10px -30px;
		            color: #FFF;
		            background: #9DC45F;
		            text-shadow: 1px 1px 1px #949494;
		            border-radius: 5px 5px 0px 0px;
		            -webkit-border-radius: 5px 5px 0px 0px;
		            -moz-border-radius: 5px 5px 0px 0px;
		            border-bottom: 1px solid #89AF4C;
		        }

		        .smart-green h1 > span {
		            display: block;
		            font-size: 11px;
		            color: #FFF;
		        }

		        .smart-green label {
		            display: block;
		            margin: 0px 0px 5px;
		        }


		        .smart-green input[type="text"], .smart-green input[type="email"], .smart-green textarea, .smart-green select {
		            color: #555;
		            height: 30px;
		            line-height: 15px;
		            width: 100%;
		            padding: 0px 0px 0px 10px;
		            margin-top: 2px;
		            border: 1px solid #E5E5E5;
		            background: #FBFBFB;
		            outline: 0;
		            -webkit-box-shadow: inset 1px 1px 2px rgba(238, 238, 238, 0.2);
		            box-shadow: inset 1px 1px 2px rgba(238, 238, 238, 0.2);
		            font: normal 14px/14px Arial, Helvetica, sans-serif;
		        }

		        .smart-green textarea {
		            height: 200px;
		            padding-top: 10px;
		            display: block;
		            font-size: 11px;
		        }


		        .smart-green .button {
		            background-color: #9DC45F;
		            border-radius: 5px;
		            -webkit-border-radius: 5px;
		            -moz-border-border-radius: 5px;
		            border: none;
		            padding: 10px 25px 10px 25px;
		            color: #FFF;
		            text-shadow: 1px 1px 1px #949494;
		        }

		        .smart-green .button:hover {
		            background-color: #80A24A;
		        }

		    </style>
		</head>
		<body>
		<form action="/form/" method="post" class="smart-green">
		    <h1>未来安全探测者
		        <span>安全无小事</span>
		    </h1>

		    <p><label><span style="font-size: 13px;">亲爱的小伙伴 !!!
		    </br></br>
		    &nbsp;&nbsp;&nbsp;&nbsp;见信好!通过未来安全探测者的安全分析,发现您的资产信息存在弱点; 请查阅附件进行修复 , thank you for readding!</span></label></p>

		</form>

		</body>
		</html>
	"""
	msgtext = MIMEText(contents, _subtype = 'html', _charset = 'UTF-8')


	# 创建MIMEMultipart对象, 附加MIMEImage的内容
	msg = MIMEMultipart()

	# MIMEMultipart对象附加MIMEText内容[html]
	msg.attach(msgtext)

	# 图片内容: MIMEMultipart对象附加MIMEImage内容[图片]
	# msg.attach(add_img('img/weekly.jpg', 'weekly'))

	# 附件:创建一个MIMEApplication对象,附加week_report.pdf 
	pdfpart = MIMEApplication(open('%s' % pdf_path, 'rb').read())
	pdfpart.add_header('Content-Disposition', 'attachment', filename='%s业务安全质量报告.pdf' % host )
	msg.attach(pdfpart)


	SUBJECT = "%s业务安全质量报告----未来安全局" % host 
	msg["SUBJECT"] = SUBJECT
	msg["From"] = EMAIL_HOST_USER
	msg["To"] = EMAIL_TO

	try:
		server = smtplib.SMTP()
		server.connect(EMAIL_HOST)
		server.login(EMAIL_HOST_USER , EMAIL_HOST_PASSWORD)
		server.sendmail(EMAIL_HOST_USER, EMAIL_TO, msg.as_string())
		server.quit()
		return True 
	except Exception as e:
		return False
Example #33
0
    def send(self,
             mail_to_list,
             cc_mail_to_list,
             bcc_mail_to_list,
             subject,
             body,
             attachement=None):
        # Make sure recipients is an array of unique elements, then format it to be a coma-separated string
        mail_to_list = list(set(mail_to_list))
        cc_mail_to_list = list(set(cc_mail_to_list))
        bcc_mail_to_list = list(set(bcc_mail_to_list))

        # Set email sender in the header, recipients, subject, and email body
        msg = MIMEMultipart()
        msg['From'] = self.FROM
        msg['To'] = ','.join(mail_to_list)
        msg['CC'] = ','.join(cc_mail_to_list)
        msg['BCC'] = ','.join(bcc_mail_to_list)
        msg['Subject'] = subject

        formatted_body = """
            <html>
                <head></head>
                <body>
                    {body}
                </body>
            </html>
        """.format(body=body)
        msg.attach(MIMEText(formatted_body, 'html'))

        # Attach file if any
        if attachement is not None:
            with open(attachement, 'r') as f:
                attachement_data = f.read()

            payload = MIMEBase('application', 'octet-stream')
            payload.set_payload(attachement_data)
            encoders.encode_base64(payload)
            payload.add_header(
                'Content-Disposition',
                'attachement; filename={}'.format(basename(attachement)))

            msg.attach(payload)
            logging.info('Payload file attached !')

        msg = msg.as_string()
        logging.info('Email successfully formatted !')

        try:
            server = SMTP(host=self.HOST, port=self.PORT)
            logging.info('Successfully connected to SMTP server !')
            server.starttls()
            server.login(user=self.ADDR, password=self.PASS)

            logging.info('Successfully logged in to email user {}'.format(
                self.ADDR))

            to_addresses = mail_to_list + cc_mail_to_list + bcc_mail_to_list
            server.sendmail(self.ADDR, to_addresses, msg)

            logging.info('Email sent to {}'.format(to_addresses))

            server.quit()

        except Exception as e:
            logging.exception('Error: {}'.format(e))
Example #34
0
tree = ET.parse(
    "C:/Program Files/LogRhythm/SmartResponse Plugins/KasperskyConfigFile.xml")

root = tree.getroot()

for elem in root.iter('item'):
    if (elem.attrib["name"] == "from"):
        mail_From = elem.text
    elif (elem.attrib["name"] == "to"):
        mail_To = elem.text
    elif (elem.attrib["name"] == "SMTP"):
        SMTP_Server = elem.text

mail_To = list(mail_To.split(","))

msg = MIMEMultipart()

subject = "Host Isolated"

html = """\

<html>

  <head></head>

  <body>

    <p>Dear Team,<br>

      <br>
Example #35
0
def sendMail(meeting_url, usersList):
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.ehlo()

    email_address = ''
    password = ''
    with open('creds.txt') as f:
        data = yaml.load(f, Loader=yaml.FullLoader)
        email_address = data['email_address']
        password = data['password']

    server.login(email_address, password)

    # subject = 'Zoom Invitation Link'
    # body = 'Click on the following link to join the meeting: ' + meeting_url

    # msg = f"Subject: {subject}\n\n{body}"

    text = """\
    Hi,
    How are you?
    Here is your Zoom meeting link: """ + meeting_url

    html = """\
    <html><center>
    <div>
    <img src="https://pbs.twimg.com/profile_images/2027772417/gng_texture_blue_180x180_400x400.gif" style="width:250px;height:250px;"
    <br>
    </div>
    <head><strong>Zoom Meeting Invitation</strong></head>
    <body>
        <p>Thank you for signing up for a Zoom meeting!<br>
        Please join the meeting at the link below.
        <br><br><h1>{meeting_url}</h1><br>
        </p>
    </body>
    </html>
    """.format(meeting_url=meeting_url)

    message = MIMEMultipart("alternative")
    message["Subject"] = "Zoom Invitation Link"
    message["From"] = email_address

    part1 = MIMEText(text, "plain")
    part2 = MIMEText(html, "html")

    message.attach(part1)
    message.attach(part2)

    regex = '^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$'

    for user in usersList:
        message["To"] = user
        if(re.search(regex, user)):
            server.sendmail(email_address, user, message.as_string())
        else:
            raise Exception("Invalid email address.")

    server.quit()
Example #36
0
# 导入相应的包
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEBase, MIMEMultipart

# MIMEText 三个主要参数
# 1.邮件内容
# 2.MIME子类型,在此案例我们用plain表示text类型
# 3.邮件编码格式
mail_mul = MIMEMultipart()
mail_text = MIMEText("Hello, i am xxxx", "plain", "utf-8")

mail_mul.attach(mail_text)
with open("x02.xml", "rb") as f:
    s = f.read()
    m = MIMEText(s, "base64", "utf-8")
    m["Content-Type"] = "application/octet-stream"
    m["Content-Disposition"] = "attachment;filename='x02.xml'"
    mail_mul.attach(m)

from_addr = "*****@*****.**"

from_pwd = "*******"

to_addr = "*****@*****.**"

#SMTP服务器地址
smtp_srv = "smtp.qq.com"

try:
    #两个参数
Example #37
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)
# Make sure all lights are off.
# Set the cleanup handler for when user hits Ctrl-C to exit
while True:
    oldIsOpen = isOpen
    isOpen = GPIO.input(DOOR_SENSOR_PIN)
    if (isOpen):
        if now is None:
          now = datetime.datetime.now()
        time.sleep(1)
        counter += 1
        #print (counter)
        #print (now)
        if(counter == 40):
            #print ("SEND EMAIL")
            msg = MIMEMultipart()
            message_template = read_template_email('message.txt')
            message = message_template.substitute(DATE_TIME=now.strftime("%Y-%m-%d %H:%M:%S"))
            msg['Subject'] = "The door is open"
            msg.attach(MIMEText(message, 'plain'))
            server.sendmail("", "", msg.as_string())
            del msg

    elif (isOpen == 0):
     time.sleep(1)
     counter = 0
     #print (counter)
     now = None

    time.sleep(0.1)
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
host_address = "9d8e7540a04f8a"
host_pass = "******"
guest_address = "*****@*****.**"
subject = "Regarding failure of rebuild.py"
content = '''Hello, 
				Developer is in the last commit regarding error . it is rebuild agin
			THANK YOU'''
message = MIMEMultipart()
message['From'] = host_address
message['To'] = guest_address
message['Subject'] = subject
message.attach(MIMEText(content, 'plain'))
session = smtplib.SMTP('smtp.mailtrap.io', 587)
session.starttls()
session.login(host_address, host_pass)
text = message.as_string()
session.sendmail(host_address, guest_address, text)
session.quit()
print('Successfully sent your mail')
Example #40
0
class SendMail(object):
    def __init__(self, smtp_server, sender, receiver, username, password,
                 data_content, app_version, app_package, app_activity):
        self.subject = "APP冷启动耗时测试结果"
        self.smtp_server = smtp_server
        self.sender = sender
        self.receiver = receiver
        self.username = username
        self.password = password
        self.data_result = data_content[0]
        self.recent_image_path = data_content[1]
        self.recent_log_path = data_content[2]
        self.app_version = app_version
        self.app_package = app_package
        self.app_activity = app_activity
        self.msg_root = MIMEMultipart('related')  # 使用related定义内嵌资源的邮件体
        self.msg_root["Subject"] = self.subject

    def mail_text(self):
        msg_text = MIMEText(
            """
        <html>
          <body>
            <p style="font-size:20px">{}:</p>
            <p style="font-size:16px;color:red">如果图中出现较大耗时情况,
            请根据X轴的系统时间点,参照邮件的log附件,查看对应系统时间点打印的日志。</p>
            <P style="font-size:16px">[ APP Version ]: {}</P>
            <P style="font-size:16px">[ APP Package Name ]: {}</P>
            <P style="font-size:16px">[ APP Activity Name ]: {}</P>
            <p style="font-size:16px">[ 平均耗时 ]: {}毫秒</p>
            <p style="font-size:16px">[ 最小耗时 ]: {}毫秒</p>
            <p style="font-size:16px;color:red">[ 最大耗时 ]: {}毫秒</p>
            <p style="font-size:16px">[ 总共测试次数 ]: {}次</p>
            <p style="font-size:16px">[ 低于平均耗时的次数 ]: {}次</p>
            <p style="font-size:16px;color:red">[ 超出平均耗时的次数 ]: {}次</p><br>
            <p><img src="cid:image1" width="1000" height="500" /></p><br>
          </body>
        </html>""".format(self.subject, self.app_version, self.app_package,
                          self.app_activity, self.data_result[0],
                          self.data_result[1], self.data_result[2],
                          self.data_result[3], self.data_result[4],
                          self.data_result[5]), "html", "utf-8")
        self.msg_root.attach(msg_text)

    def mail_image(self):
        with open(self.recent_image_path, 'rb') as fp:
            msg_image = MIMEImage(fp.read())
        msg_image.add_header('Content-ID', '<image1>')
        self.msg_root.attach(msg_image)

    def mail_log_attachment(self):
        with open(self.recent_log_path, 'rb') as fp:
            msg_log = MIMEText(fp.read(), 'base64', 'utf-8')
        msg_log["Content-Type"] = "application/octet-stream"
        msg_log["Content-Disposition"] = "attachment; filename=log.txt"
        self.msg_root.attach(msg_log)

    def send_mail(self):
        try:
            server = smtplib.SMTP_SSL(self.smtp_server, 465, timeout=10)
            server.set_debuglevel(0)
            server.login(self.username, self.password)
            server.sendmail(self.sender, self.receiver,
                            self.msg_root.as_string())
            server.quit()
        except smtplib.SMTPException as msg:
            print(msg)
Example #41
0
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

fromaddr = "*****@*****.**"
toaddr = "*****@*****.**"

msg = MIMEMultipart()

msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "SUBJECT OF THE EMAIL"

body = "TEXT YOU WANT TO SEND"

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

filename = "unity.sql"
attachment = open("unity.sql", "rb")

part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)

msg.attach(part)

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
Example #42
0
class SendMailDealer:
    def __init__(self,
                 user,
                 passwd,
                 smtp,
                 port,
                 usetls=True,
                 debug_level=0,
                 filename=None):
        self.mailUser = user
        self.mailPassword = passwd
        self.smtpServer = smtp
        self.smtpPort = int(port)
        if self.smtpPort not in [25]:
            self.useSSL = True
            self.mailServer = smtplib.SMTP_SSL(self.smtpServer, self.smtpPort)
        else:
            self.useSSL = False
            self.mailServer = smtplib.SMTP(self.smtpServer, self.smtpPort)
        self.mailServer.set_debuglevel(debug_level)
        self.usetls = usetls
        self.method = 'SMTP'
        self.filename = filename
        self.mail_init()

    def __del__(self):
        try:
            self.mailServer.close()
        except Exception as e:
            logger.warning(e)
            logger.warning("mailServer None exist")

    def set_debug_level(self, level):
        self.mailServer.set_debuglevel(level)

    def mail_init(self, ehlo=None):
        self.mailServer.ehlo(ehlo)
        if self.usetls and not self.useSSL:
            try:
                self.mailServer.starttls()
                self.mailServer.ehlo(ehlo)
            except Exception as e:
                logger.error(e)
                logger.error(
                    u"{} This service is not supported with high probability STARTTLS"
                    .format(self.smtpServer))
        self.mailServer.login(self.mailUser, self.mailPassword)

    def addTextPart(self, text, text_type):
        self.msg.attach(MIMEText(text, text_type))

    # add email message(MIMETEXT,MIMEIMAGE,MIMEBASE...)
    def addPart(self, part):
        self.msg.attach(part)

    def sendMail(self,
                 to_email,
                 info=None,
                 subject=None,
                 content=None,
                 mail_from=None,
                 mime_from=None,
                 reply_to=None,
                 return_path=None,
                 sender=None,
                 ehlo=None,
                 to=None,
                 mime_from1=None,
                 mime_from2=None,
                 image=None,
                 defense=None,
                 **headers):
        """
        :param to_email: 
        :param info: 
        :param subject: 
        :param content: 
        :param mail_from:
        :param mime_from:
        :param reply_to:
        :param return_path:
        :param sender:
        :param ehlo:
        :param headers:
        :return:
        """
        self.msg = MIMEMultipart()
        if ehlo is not None:
            self.mailServer.ehlo(ehlo)
        if to is not None:
            self.msg['To'] = to
        else:
            self.msg['To'] = to_email
        if not self.msg['To']:
            logger.error(u"Please specify MIME TO")
            return
        if mail_from is None:
            mail_from = self.mailUser
        if mime_from is None:
            mime_from = mail_from
        # if mime_from != 'NULL':
        #     self.msg['From'] = mime_from
        if mime_from1:
            self.msg['From'] = mime_from1
            self.msg.add_header('From', mime_from)
        elif mime_from2:
            self.msg['From'] = mime_from
            self.msg.add_header('From', mime_from2)
        else:
            self.msg['From'] = mime_from
        # else:
        #     try:
        #         mime_from = headers['From']
        #     except Exception as e:
        #         logger.error(e)
        #         mime_from = 'NULL'
        for h in headers:
            self.msg.add_header(str(h), str(headers[h]))
        if info is None:
            info = u"normal test"
        if subject is None:
            subject = "[{} {}] {} --> {}".format(self.method, info, mime_from,
                                                 to_email)
        self.msg['Subject'] = "{}".format(subject)
        # 自定义头部
        if reply_to is not None:
            self.msg['Reply'] = reply_to
        if sender is not None:
            self.msg['Sender'] = sender
        # if content is None:
        #     content = "-" * 100 + "\r\n"
        #     content += """If you see this email, it means that you may be affected by email spoofing attacks.\n"""
        #     content += """This email uses '{}' to attack.""".format(info)
        #     content = """[{method} {info}] {mime_from} --> {to_email} \r\n""".format(method=self.method,
        #                                                                              mime_from=mime_from,
        #                                                                              to_email=to_email, info=info)
        # if defense:
        #     content += '\r\n' + '-' * 100 + '\r\n'
        #     content += '''Defense measures: {defense}\n'''.format(defense=defense)
        # content += "-" * 100 + "\r\n"
        # content += """Email headers information:\r\nEnvelope.From: {mail_from}\nMIME.From: {mime_from}\nSender: {sender}\nReturn path: {return_path}""".format(
        #         mail_from=mail_from, sender=sender, return_path=return_path, mime_from=mime_from)
        mime_headers = self.msg.as_string()
        index = mime_headers.find("--=======")
        mime_headers = mime_headers[:index].strip()
        mime_headers = """MAIL From: {mail_from}\n""".format(
            mail_from=mail_from) + mime_headers
        mime_headers = mime_headers.replace("\n", "\n\n")
        mime_headers += "\r\n\r\n" + "-" * 100 + "\r\n"
        content += mime_headers
        # logger.debug(mime_headers)

        _attach = MIMEText(content)
        # _attach = MIMEText(content, 'html', 'utf-8')
        self.msg.attach(_attach)
        if image:
            fp = open("./uploads/" + image, 'rb')
            images = MIMEImage(fp.read())
            fp.close()
            images.add_header('Content-ID', '<image1>')
            self.msg.attach(images)
        if self.filename:
            att1 = MIMEText(
                open('./uploads/' + self.filename, 'rb').read(), 'base64',
                'utf-8')
            att1["Content-Type"] = 'application/octet-stream'
            att1["Content-Disposition"] = 'attachment; filename="{}"'.format(
                self.filename)
            self.msg.attach(att1)
        # logger.debug("-" * 50)
        # logger.debug(self.msg.as_string())
        # logger.debug("-" * 50)
        self.mailServer.sendmail(mail_from, to_email, self.msg.as_string())
Example #43
0
from smtplib import SMTP
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

if __name__ == '__main__':
    from_addr = '*****@*****.**'
    email_pass = '******'
    to_addrs = ['*****@*****.**']
    comma_char = ','
    message = MIMEMultipart()
    message['From'] = from_addr
    message['To'] = comma_char.join(to_addrs)
    message['Subject'] = "Chores email test"
    message.attach(
        MIMEText('test email message from smtplib w/ mime parts', 'plain'))

    smtp = SMTP('smtp.gmail.com', 587)
    smtp.ehlo()
    smtp.starttls()
    smtp.ehlo()
    smtp.login(from_addr, email_pass)


    smtp.sendmail(from_addr,\
     to_addrs,\
     str(message))
    smtp.quit()
Example #44
0
def forgotcredetials(request):

    bug_hunter = []

    if request.method == "POST":
        try:
            lostuser = request.POST['email']

        except Exception as e:
            bug_hunter.append("Invalid input")
            return render(request,
                          "login/forgot.html",
                          context={"error": bug_hunter})

        else:
            try:
                userdata = Signup.objects.get(email=lostuser)
            except Signup.DoesNotExist as e:
                bug_hunter.append("Email not registered with us")
                return render(request,
                              "login/forgot.html",
                              context={"error": bug_hunter})
            else:
                if v.validate_email(lostuser):
                    hashcode = string.digits + string.ascii_letters + string.digits + string.digits
                    hashcode = "".join(
                        [random.choice(hashcode) for value in range(10)])
                    sender = "*****@*****.**"
                    receiver = lostuser
                    # message = """From: %s
                    # To: %s,
                    # Content-Type:text/html,
                    # Mime-version:1.0,
                    # Content-disposition: text,
                    # Subject:Vibes reset password is: %s,
                    # """%("*****@*****.**",receiver , hashcode)
                    message = "Your recovery code is <strong>%s </strong><a href='devcodes.herokuapp.com/login/updatereset/'> reset link</a>" % hashcode
                    mess = MIMEMultipart("alternatives")
                    mess["From"] = "*****@*****.**"
                    mess["To"] = receiver
                    mess["Subject"] = "Devcodes recovery code."
                    message = MIMEText(message, "html")
                    mess.attach(message)
                    try:
                        obj = sm.SMTP('smtp.gmail.com', 587)
                        obj.starttls()
                        obj.login("*****@*****.**", "[email protected]")
                        obj.sendmail(sender, receiver, mess.as_string())
                        obj.close()
                    except Exception as error:
                        print("Error: {}".format(error))
                        bug_hunter.append(
                            "Connection could not be established")
                        # bug_hunter.append(error)
                        return render(request,
                                      "login/forgot.html",
                                      context={"error": bug_hunter})

                    else:
                        Recoverdata.objects.create(
                            uid_id=Signup.objects.get(email=receiver).uid,
                            secret_code=hashcode)
                        print(
                            "Message sent successfully to {}".format(receiver))
                        print("Exiting the mail client program")
                        return render(request, "login/thanks.html")
                else:
                    return render(request,
                                  "login/forgot.html",
                                  context={"error": bug_hunter})
    else:
        return render(request,
                      "login/forgot.html",
                      context={"error": bug_hunter})
Example #45
0
 print('邮件主送对象:>>', receiver)
 cc = '**<******@**.com>'  #邮件抄送者
 print('邮件抄送对象:>>', cc)
 bcc = '**<******@**.com>'  #邮件密送者
 print('邮件密送对象:>>', bcc)
 allreceivers = '%s,%s,%s' % (receiver, cc, bcc)  #合并所有接受者
 emiless = re.findall(r'[0-9a-zA-Z._]+@[0-9a-zA-Z._]+\.[0-9a-zA-Z._]+',
                      allreceivers)  #匹配邮箱
 emiles = set(emiless)  #去重
 #分割邮箱名和邮箱
 toaddrs = []
 for emile in emiles:
     for i in emile.split(','):
         toaddrs.append(i)
 print('邮件发送给:>>', toaddrs)
 m = MIMEMultipart()
 #邮件正文
 content = '这是正文部分。<a href="http://www.baidu.com">跳转页面</a>'
 # plain 文本
 # html  网页
 textApart = MIMEText(content, 'html', 'utf-8')
 m.attach(textApart)
 #邮件附件
 Files = ['smail.py', '这是PDF.pdf', '这是压缩文件.zip', '这是图片.png']
 print('邮件包含的附件:>>', Files)
 number = 0
 for f in Files:
     fnApart = 'Apart%s' % number
     print(fnApart)
     fnApart = MIMEApplication(open(f, 'rb').read())
     fnApart.add_header('Content-Disposition',
Example #46
0
    while True:# loop infinito
        schedule.run_pending()
        time.sleep(1)

# Para fazer string constructor utilize o f antes da string
except IndexError as e:
    email_body = f'''
        O bot apresento problemas, favor verificar:
        Erro: {e}
    '''

    from_email = '*****@*****.**'
    password = '******'
    to_email = '*****@*****.**'

    message = MIMEMultipart()
    message['From'] = from_email
    message['To'] = to_email
    message['Subject'] = 'Bot falhou'

    # Corpo do E-mail com anexos
    message.attach(MIMEText(email_body, 'plain'))

    # Create SMTP session for sending the mail
    session = smtplib.SMTP('smtp.gmail.com', 587)  # Usuário do Gmail com porta
    session.starttls()  # Habilita a segurança
    session.login(from_email, password)  # Login e senha de quem envia o e-mail
    text = message.as_string()
    session.sendmail(from_email, to_email, text)
    session.quit()
Example #47
0
def main(sender, recipients, subject, body, is_reminder, reminder_mails,
         reminder_numbers):

    global data
    chk_folder = Path('inbox_attachment_dir')
    if (chk_folder.is_dir()):
        print("The  folder is available")
    else:
        print("The folder is not available")

    gmail_password = '******'
    #recipients = ['*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**']

    email_sent = dbcreate()
    # Create the enclosing (outer) message
    outer = MIMEMultipart()
    outer['Subject'] = subject

    outer['From'] = sender
    outer['Message-ID'] = email.utils.make_msgid()
    outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'

    # List of attachments
    attachments = []
    attachments_folder_name = subject + str(outer['Message-ID'])
    # Add the attachments to the message
    for file in attachments:
        try:
            with open(file, 'rb') as fp:
                msg = MIMEBase('application', "octet-stream")
                msg.set_payload(fp.read())
            encoders.encode_base64(msg)
            msg.add_header('Content-Disposition',
                           'attachment',
                           filename=os.path.basename(file))
            outer.attach(msg)
        except:
            print("Unable to open one of the attachments. Error: ",
                  sys.exc_info()[0])
            raise
        '''
        try:
            with open(file,'rb') as fp:
        '''

    # Send the email
    try:
        with smtplib.SMTP('smtp.gmail.com', 587) as s:
            s.ehlo()
            s.starttls()
            s.ehlo()
            s.login(sender, gmail_password)
            for recipient in recipients:
                outer['To'] = recipient
                outer.attach(MIMEText(body, "html"))
                composed = outer.as_string()

                s.sendmail(sender, recipient, composed)
                del (outer['To'])
            s.close()
        print("Email sent!")
        #re = datetime.datetime.now() + datetime.timedelta(minutes=1)
        #re = re.timestamp()*1000
        email_sent.insert_one({
            'to': recipients,
            'from': sender,
            'subject': outer['Subject'],
            'MessageID': str(outer['Message-ID']),
            'DateTime': datetime.datetime.now(),
            'time': time.time(),
            'attachments': attachments,
            'message': body,
            #'reminder':re,
            'reminder': data,
            'reminder_mails': reminder_mails,
            'reminder_numbers': reminder_numbers,
            'is_reminder': is_reminder
        })

    except:
        print("Unable to send the email. Error: ", sys.exc_info()[0])
        raise
Example #48
0
</div>
</div>
<img src="cid:image1"/>
</body>
</html>
    """

# # 第三方 SMTP 服务
mail_host = "smtp.edspay.com"  # 设置服务器
mail_user = "******"  # 用户名
mail_pass = "******"  # 口令
sender = '*****@*****.**'
receivers = ['*****@*****.**',
             '*****@*****.**']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
# 定义邮件内容
msgRoot = MIMEMultipart('related')
# 指定图片为当前目录
msgRoot['From'] = '*****@*****.**'
msgRoot['To'] = '*****@*****.**'
subject = 'Python SMTP 邮件测试'
msgRoot['Subject'] = Header(subject, 'utf-8')
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
msgAlternative.attach(MIMEText(html, 'html', 'utf-8'))
fp = open('examples.jpg', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
# 定义图片 ID,在 HTML 文本中引用
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)
smtpObj = smtplib.SMTP()
Example #49
0
def build_userdata(resource,
                   userdata=None,
                   instance_user=None,
                   user_data_format='HEAT_CFNTOOLS'):
    '''
    Build multipart data blob for CloudInit which includes user-supplied
    Metadata, user data, and the required Heat in-instance configuration.

    :param resource: the resource implementation
    :type resource: heat.engine.Resource
    :param userdata: user data string
    :type userdata: str or None
    :param instance_user: the user to create on the server
    :type instance_user: string
    :param user_data_format: Format of user data to return
    :type user_data_format: string
    :returns: multipart mime as a string
    '''

    if user_data_format == 'RAW':
        return userdata

    def make_subpart(content, filename, subtype=None):
        if subtype is None:
            subtype = os.path.splitext(filename)[0]
        msg = MIMEText(content, _subtype=subtype)
        msg.add_header('Content-Disposition', 'attachment', filename=filename)
        return msg

    def read_cloudinit_file(fn):
        data = pkgutil.get_data('heat', 'cloudinit/%s' % fn)
        data = data.replace('@INSTANCE_USER@', instance_user
                            or cfg.CONF.instance_user)
        return data

    attachments = [(read_cloudinit_file('config'), 'cloud-config'),
                   (read_cloudinit_file('boothook.sh'), 'boothook.sh',
                    'cloud-boothook'),
                   (read_cloudinit_file('part_handler.py'), 'part-handler.py'),
                   (userdata, 'cfn-userdata', 'x-cfninitdata'),
                   (read_cloudinit_file('loguserdata.py'), 'loguserdata.py',
                    'x-shellscript')]

    if 'Metadata' in resource.t:
        attachments.append(
            (json.dumps(resource.metadata), 'cfn-init-data', 'x-cfninitdata'))

    attachments.append(
        (cfg.CONF.heat_watch_server_url, 'cfn-watch-server', 'x-cfninitdata'))

    attachments.append((cfg.CONF.heat_metadata_server_url,
                        'cfn-metadata-server', 'x-cfninitdata'))

    # Create a boto config which the cfntools on the host use to know
    # where the cfn and cw API's are to be accessed
    cfn_url = urlutils.urlparse(cfg.CONF.heat_metadata_server_url)
    cw_url = urlutils.urlparse(cfg.CONF.heat_watch_server_url)
    is_secure = cfg.CONF.instance_connection_is_secure
    vcerts = cfg.CONF.instance_connection_https_validate_certificates
    boto_cfg = "\n".join([
        "[Boto]", "debug = 0",
        "is_secure = %s" % is_secure,
        "https_validate_certificates = %s" % vcerts, "cfn_region_name = heat",
        "cfn_region_endpoint = %s" % cfn_url.hostname,
        "cloudwatch_region_name = heat",
        "cloudwatch_region_endpoint = %s" % cw_url.hostname
    ])
    attachments.append((boto_cfg, 'cfn-boto-cfg', 'x-cfninitdata'))

    subparts = [make_subpart(*args) for args in attachments]
    mime_blob = MIMEMultipart(_subparts=subparts)

    return mime_blob.as_string()
Example #50
0
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import socket

#recuperer le nom d'utilisateur
USER_NAME = getpass.getuser()

#Initialisation
fromaddr = "*****@*****.**"

#Adresse email dest :vous allez recevoir le fichier key_log.txt sur cet email
toaddr = "*****@*****.**"
#Pour voir les fichiers .txt , veuillez utiliser le mot de passe suivant : "python1m"

msg = MIMEMultipart()

msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Bonjour, vous trouverez ci joint le fichier key_log.txt, Bonne journee!"

m = "Nom d'utilisateur  : %s" % USER_NAME

#message envoye avec le fichier key_log.txt
body = "Fichier envoye avec succes \n Adresse IP de l'utilisateur : %s\n" % [
    ip for ip in socket.gethostbyname_ex(socket.gethostname())[2]
    if not ip.startswith("127.")
][0]
n = body + m
msg.attach(MIMEText(n, 'plain'))
Example #51
0
def send_email(movies, to_addr, to_user):
    def _format_addr(s):
        name, addr = parseaddr(s)
        return formataddr((Header(name, 'utf-8').encode(), addr))

    from_server = 'smtp.xx.com'  # the smtp server of sender
    from_addr = '*****@*****.**'  # the address of sender
    from_pass = '******'  # the passwd of sender
    from_user = '******'  # the nickname of sender

    print('Start to send email to %s' % to_addr)
    mail_title = '豆瓣热映电影 %s' % time.strftime('%Y-%m-%d',
                                             time.localtime(time.time()))
    mail_body = ''
    for movie in movies:
        mail_body += '<p>' + '=' * 8 + '</p>'
        mail_body += '<p>片名: %s</p>' % movie['title']
        mail_body += '<p>年份: %s</p>' % movie['year']
        if movie['rate'] == '0':  # too fewer rater</p>
            mail_body += '<p>评分: 暂无评分'
        else:
            mail_body += '<p>评分: %s</p>' % movie['rate']
        mail_body += '<p>评价人数: %s</p>' % movie['rater']
        mail_body += '<p>时长: %s</p>' % movie['duration']
        mail_body += '<p>国家地区: %s</p>' % movie['region']
        mail_body += '<p>导演: %s</p>' % movie['director']
        mail_body += '<p>演员: %s</p>' % ' '.join(movie['actors'])
        mail_body += '<p>海报:</p>'
        mail_body += '<p><img src="cid:%s"></p>' % movie['cover_file'].split(
            '/')[-1].split('.')[0]
        mail_body += '<p>' + '=' * 8 + '</p>'

    msg = MIMEMultipart('related')
    msg['From'] = _format_addr('%s(%s) <%s>' %
                               (from_user, get_local_ip(), from_addr))
    msg['To'] = _format_addr('%s <%s>' % (to_user, to_addr))
    msg['Subject'] = Header(mail_title, 'utf-8').encode()
    msgAlternative = MIMEMultipart('alternative')
    msg.attach(msgAlternative)
    msg_text = MIMEText(mail_body, 'html', 'utf-8')
    msgAlternative.attach(msg_text)
    # insert images
    for movie in movies:
        with open(movie['cover_file'], 'rb') as f:
            msg_image = MIMEImage(f.read())
        msg_image.add_header(
            'Content-ID',
            '<%s>' % movie['cover_file'].split('/')[-1].split('.')[0])
        msg.attach(msg_image)
    # ssl login
    smtp = SMTP_SSL(from_server)
    smtp.set_debuglevel(0)
    smtp.ehlo(from_server)
    smtp.login(from_addr, from_pass)
    # send email
    smtp.sendmail(from_addr, to_addr, msg.as_string())
    smtp.quit()
    print('Send email to %s successfully' % to_addr)
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.base import MIMEBase
from email.mime.application import MIMEApplication
from email.header import Header
# 发件人地址,通过控制台创建的发件人地址
username = '******'
# 发件人密码,通过控制台创建的发件人密码
password = '******'
# 自定义的回复地址
replyto = '*****@*****.**'
# 收件人地址或是地址列表,支持多个收件人,最多30个
#rcptto = ['***', '***']
rcptto = '*****@*****.**'
# 构建alternative结构
msg = MIMEMultipart('alternative')
msg['Subject'] = Header('自定义信件主题')
msg['From'] = '%s <%s>' % (Header('自定义发信昵称'), username)
msg['To'] = rcptto
msg['Reply-to'] = replyto
msg['Message-id'] = email.utils.make_msgid()
msg['Date'] = email.utils.formatdate() 
# 构建alternative的text/plain部分
textplain = MIMEText('自定义TEXT纯文本部分', _subtype='plain', _charset='UTF-8')
msg.attach(textplain)
# 构建alternative的text/html部分
texthtml = MIMEText('自定义HTML超文本部分', _subtype='html', _charset='UTF-8')
msg.attach(texthtml)
# 发送邮件
try:
    client = smtplib.SMTP()
Example #53
0
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
mail_content = '''Log file has been sent
'''
#The mail addresses and password
sender_address = '*****@*****.**'
sender_pass = '******'
receiver_address = '*****@*****.**'
#Setup the MIME
message = MIMEMultipart()
message['From'] = sender_address
message['To'] = receiver_address
message['Subject'] = 'Log file generated by Monitor Service'
#The subject line
#The body and the attachments for the mail
message.attach(MIMEText(mail_content, 'plain'))
attach_file_name = 'log.txt'
attach_file = open(attach_file_name, 'rb')  # Open the file as binary mode
payload = MIMEBase('application', 'octate-stream', Name=attach_file_name)
payload.set_payload((attach_file).read())
encoders.encode_base64(payload)  #encode the attachment
#add payload header with filename
payload.add_header('Content-Decomposition',
                   'attachment',
                   filename=attach_file_name)
Example #54
0
    def sendMail(self,
                 to_email,
                 info=None,
                 subject=None,
                 content=None,
                 mail_from=None,
                 mime_from=None,
                 reply_to=None,
                 return_path=None,
                 sender=None,
                 ehlo=None,
                 to=None,
                 mime_from1=None,
                 mime_from2=None,
                 image=None,
                 defense=None,
                 **headers):
        """
        :param to_email: 
        :param info: 
        :param subject: 
        :param content: 
        :param mail_from:
        :param mime_from:
        :param reply_to:
        :param return_path:
        :param sender:
        :param ehlo:
        :param headers:
        :return:
        """
        self.msg = MIMEMultipart()
        if ehlo is not None:
            self.mailServer.ehlo(ehlo)
        if to is not None:
            self.msg['To'] = to
        else:
            self.msg['To'] = to_email
        if not self.msg['To']:
            logger.error(u"Please specify MIME TO")
            return
        if mail_from is None:
            mail_from = self.mailUser
        if mime_from is None:
            mime_from = mail_from
        # if mime_from != 'NULL':
        #     self.msg['From'] = mime_from
        if mime_from1:
            self.msg['From'] = mime_from1
            self.msg.add_header('From', mime_from)
        elif mime_from2:
            self.msg['From'] = mime_from
            self.msg.add_header('From', mime_from2)
        else:
            self.msg['From'] = mime_from
        # else:
        #     try:
        #         mime_from = headers['From']
        #     except Exception as e:
        #         logger.error(e)
        #         mime_from = 'NULL'
        for h in headers:
            self.msg.add_header(str(h), str(headers[h]))
        if info is None:
            info = u"normal test"
        if subject is None:
            subject = "[{} {}] {} --> {}".format(self.method, info, mime_from,
                                                 to_email)
        self.msg['Subject'] = "{}".format(subject)
        # 自定义头部
        if reply_to is not None:
            self.msg['Reply'] = reply_to
        if sender is not None:
            self.msg['Sender'] = sender
        # if content is None:
        #     content = "-" * 100 + "\r\n"
        #     content += """If you see this email, it means that you may be affected by email spoofing attacks.\n"""
        #     content += """This email uses '{}' to attack.""".format(info)
        #     content = """[{method} {info}] {mime_from} --> {to_email} \r\n""".format(method=self.method,
        #                                                                              mime_from=mime_from,
        #                                                                              to_email=to_email, info=info)
        # if defense:
        #     content += '\r\n' + '-' * 100 + '\r\n'
        #     content += '''Defense measures: {defense}\n'''.format(defense=defense)
        # content += "-" * 100 + "\r\n"
        # content += """Email headers information:\r\nEnvelope.From: {mail_from}\nMIME.From: {mime_from}\nSender: {sender}\nReturn path: {return_path}""".format(
        #         mail_from=mail_from, sender=sender, return_path=return_path, mime_from=mime_from)
        mime_headers = self.msg.as_string()
        index = mime_headers.find("--=======")
        mime_headers = mime_headers[:index].strip()
        mime_headers = """MAIL From: {mail_from}\n""".format(
            mail_from=mail_from) + mime_headers
        mime_headers = mime_headers.replace("\n", "\n\n")
        mime_headers += "\r\n\r\n" + "-" * 100 + "\r\n"
        content += mime_headers
        # logger.debug(mime_headers)

        _attach = MIMEText(content)
        # _attach = MIMEText(content, 'html', 'utf-8')
        self.msg.attach(_attach)
        if image:
            fp = open("./uploads/" + image, 'rb')
            images = MIMEImage(fp.read())
            fp.close()
            images.add_header('Content-ID', '<image1>')
            self.msg.attach(images)
        if self.filename:
            att1 = MIMEText(
                open('./uploads/' + self.filename, 'rb').read(), 'base64',
                'utf-8')
            att1["Content-Type"] = 'application/octet-stream'
            att1["Content-Disposition"] = 'attachment; filename="{}"'.format(
                self.filename)
            self.msg.attach(att1)
        # logger.debug("-" * 50)
        # logger.debug(self.msg.as_string())
        # logger.debug("-" * 50)
        self.mailServer.sendmail(mail_from, to_email, self.msg.as_string())
Example #55
0
 def __initialize(self):
     self._session_message = MIMEMultipart()
Example #56
0
File: smtp.py Project: pang43/Study
# password = input('Password: '******'lt970106'
#to_addr = input('To (Group send , separate): ')
to_addr = '*****@*****.**'
# smtp_server = input('SMTP server: ')    # smtp.163.com / smtp.qq.com
smtp_server = 'smtp.163.com'
mail_head = input('Mail Head: ')

context = []
eof = input('Input msg, Input your eof char: ')
print('-' * 20)
while True:
    line = input().strip()
    if line == eof: break
    context.append(line)
print('-' * 20)

msg = MIMEMultipart()
msg.attach(MIMEText('\n'.join(context), 'plain', 'utf-8'))
msg['From'] = from_addr
msg['To'] = to_addr
msg['Subject'] = Header(mail_head, 'utf-8').encode()

server = smtplib.SMTP(smtp_server, 25)
server.login(from_addr, password)
server.sendmail(from_addr, list(to_addr.split(',')), msg.as_string())
server.quit()

print('-' * 20)
print('Send successfully')
def sendReportMail(report_files, conf_file):
    print report_files, conf_file
    report_name_list = []
    for i in range(len(report_files)):
        report_name = report_files[i].split('\\')[-1]
        report_name_list.append(report_name)
    print report_name_list
    result = {}
    return_conf = switchCase_tool(conf_file)
    # 邮件服务器
    mail_host = return_conf[conf_file]['mail_host']
    # 邮件服务器端口
    mail_port = return_conf[conf_file]['mail_port']
    # 发件人地址
    mail_user = return_conf[conf_file]['mail_user']
    # 发件人密码
    mail_pwd = return_conf[conf_file]['mail_pwd']
    # 邮件标题
    mail_subject = return_conf[conf_file]['mail_subject'] + \
        '_{0}'.format(
            '_'.join(report_name_list[0].strip('.html').split('_')[-2:]))
    # 收件人地址list
    mail_to = return_conf[conf_file]['mail_to']

    # 判断报告文件是否存在
    if len(report_files) == 0:
        # if not os.path.exists(report_file):
        return jsonify(dict(desc=u'测试报告文件不存在:{0},<strong>先运行一次测试吧!</strong>'.format(report_files)))
    else:
        content_l = []
        for i in range(len(report_files)):
            # 读取测试报告内容
            print str(report_files[i])
            with open(str(report_files[i]), 'r') as f:
                content = f.read().decode('utf-8')
            content_l.append(content)

        content_lists = ''.join(content_l)
        msg = MIMEMultipart('mixed')
        # 添加邮件内容
        msg_html = MIMEText(
            content_lists, _subtype='html', _charset='utf-8')
        msg.attach(msg_html)
        msg['Subject'] = mail_subject
        msg['From'] = mail_user
        msg['To'] = mail_to

        # # 添加附件
        msg_attachment = MIMEText(content_lists, 'html', 'utf-8')
        msg_attachment["Content-Disposition"] = 'attachment; filename="{0}"'.format(
            report_name_list[i])
        msg_attachment["Content-Type"] = 'application/octet-stream'
        msg.attach(msg_attachment)

    try:
        # 连接邮件服务器
        s = smtplib.SMTP()
        s.connect(mail_host, mail_port)
        # 登陆
        s.login(mail_user, mail_pwd)
        # 发送邮件
        s.sendmail(mail_user, mail_to, msg.as_string())
        # 退出
        s.quit()
        result['desc'] = u'测试报告发送成功'

    except Exception as e:
        result['desc'] = u'测试报告发送失败:{0}'.format(e)

    return result
Example #58
-1
    def run(self):
        account = str(self.account)
        # Create the enclosing (outer) message
        outer = MIMEMultipart()
        outer['Subject'] = 'mask{0}mask_{1}'.format(self.index, str(self.filename))
        outer['To'] = account
        outer['From'] = account
        outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'

        ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)

        fp = open(str(self.filename), 'rb')
        msg = MIMEBase(maintype, subtype)
        #msg.set_payload(encodebytes(fp.read()).decode())
        msg.set_payload(fp.read())
        fp.close()
        encoders.encode_base64(msg)
    #    msg.add_header('Content-Transfer-Encoding', 'base64')
        msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(str(self.filename)))
        outer.attach(msg)
        # Send the message
        composed = outer.as_string()
        if DEBUG:
            fp = open("./output", 'w')
            fp.write(composed)
            fp.close()
        else:
            s = smtplib.SMTP()
            s.set_debuglevel(DEBUG)
            s.connect(self.smtp_server)
            s.login(account, self.password)
            s.sendmail(account, account, composed)
            s.quit()
Example #59
-1
def sendEmail():
    #This sends an email containing any type of attachment
    emailfrom = "*****@*****.**"
    emailto = ["*****@*****.**"]
    fileToSend = "/home/pi/picurity-system/videos/SurveillanceFootage.h264"
    username = "******"
    password = "******"
    msg = MIMEMultipart()
    msg["From"] = emailfrom
    msg["To"] = ", ".join(emailto)
    msg["Subject"] = "Motion Has Been Detected: View Attached Clip"
    msg.preamble = "Motion Has Been Detected: View Attached Clip"
    ctype, encoding = mimetypes.guess_type(fileToSend)
    if ctype is None or encoding is not None:
        ctype = "application/octet-stream"
    maintype, subtype = ctype.split("/", 1)
    fp = open(fileToSend, "rb")
    attachment = MIMEBase(maintype, subtype)
    attachment.set_payload(fp.read())
    fp.close()
    encoders.encode_base64(attachment)
    attachment.add_header("Content-Disposition", "attachment", filename=fileToSend)
    msg.attach(attachment)
    server = smtplib.SMTP("smtp.gmail.com:587")
    server.starttls()
    server.login(username,password)
    server.sendmail(emailfrom, emailto, msg.as_string())
    server.quit()
Example #60
-1
    def test_mime_gzip_compressed(self):
        """Tests that individual message gzip encoding works."""

        def gzip_part(text):
            return MIMEApplication(gzip_text(text), 'gzip')

        base_content1 = '''
#cloud-config
a: 2
'''

        base_content2 = '''
#cloud-config
b: 3
c: 4
'''

        message = MIMEMultipart('test')
        message.attach(gzip_part(base_content1))
        message.attach(gzip_part(base_content2))
        ci = stages.Init()
        ci.datasource = FakeDataSource(str(message))
        new_root = tempfile.mkdtemp()
        self.addCleanup(shutil.rmtree, new_root)
        self.patchUtils(new_root)
        self.patchOS(new_root)
        ci.fetch()
        ci.consume_data()
        contents = util.load_file(ci.paths.get_ipath("cloud_config"))
        contents = util.load_yaml(contents)
        self.assertTrue(isinstance(contents, dict))
        self.assertEquals(3, len(contents))
        self.assertEquals(2, contents['a'])
        self.assertEquals(3, contents['b'])
        self.assertEquals(4, contents['c'])