Esempio n. 1
0
    def sendMail(cfg, bodyDatas, title):
        to_addr = cfg.EMail

        subject = '竞标提示:人脸识别'
        # msg = MIMEText('你好', 'text', 'utf-8')  # 中文需参数‘utf-8’,单字节字符不需要
        # msg['Subject'] = Header(subject, 'utf-8')

        msg = MIMEMultipart()
        msg['From'] = SEND_ADDRESS
        msg['To'] = to_addr
        # msg['Cc'] = ccaddr
        msg['Subject'] = "竞标提示===>>" + title

        body = "竞标提示:请关注以下新增招标"
        for one in bodyDatas:
            body = "%s \n    %s" % (body, one)

        body = body.encode("utf-8")
        msg.attach(MIMEText(body, 'plain'))

        smtp = smtplib.SMTP()
        smtp.connect(SMTP_SERVER)
        smtp.ehlo()
        smtp.starttls()
        smtp.ehlo()
        smtp.set_debuglevel(0)
        smtp.login(SEND_ADDRESS, MAIL_PASSWORD)
        smtp.sendmail(SEND_ADDRESS, to_addr, msg.as_string())
        smtp.quit()
Esempio n. 2
0
    def _send_new_password(self):
        player_login = self.line_edit_player_login.text()
        try:
            from_adress = "*****@*****.**"
            to_adress = ui_defs.players_infos(player_login)["email"]

            email_to_send = MIMEMultipart()
            email_to_send['From'] = from_adress
            email_to_send['To'] = to_adress
            email_to_send['Subject'] = 'New Time Bomb Password'

            new_password = ui_defs.generate_random_password()
            self._assign_password_to_player(player_login, new_password)
            email_body = (
                'Your new time bomb password : '******'ll could change it in your preferences.\n\nSee you soon in game!"
            )
            email_to_send.attach(MIMEText(email_body, 'plain'))

            gmail_server = smtplib.SMTP('smtp.gmail.com', 587)
            gmail_server.starttls()
            gmail_server.login(from_adress, "TimeBomb78+")
            gmail_server.sendmail(from_adress, to_adress, str(email_to_send))
            gmail_server.quit()

            ui_defs.message_box('OK', 'A new password has been send.')

            self.close()

        except KeyError:
            ui_defs.message_box('Wrong Login', 'This login doesn\'t exist.')
Esempio n. 3
0
def send_email(from_address, to_address, body, SUBJECT = ""): 
   #from_address = "*****@*****.**"
   #to_address = from_address
   #SUBJECT = "THIS IS A TEST"

   PASSWORD = ""

   server = smtplib.SMTP('smtp.gmail.com', 587)
   server.starttls()
   server.login(from_address, PASSWORD)


   msg = MIMEMultipart()
   msg['From']    = from_address
   msg['To']      = to_address
   msg['Subject'] = SUBJECT

   # Input Message body text below:
   #body = "This is a test email, generated by send_email.py\nThis text should be on a new line."

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


   text = msg.as_string()

   server.sendmail(from_address, to_address, text)
   server.quit()
Esempio n. 4
0
def mail_message_to_mime_message(protocol_message):
  """Generate a MIMEMultitype message from protocol buffer.

  Generates a complete MIME multi-part email object from a MailMessage
  protocol buffer.  The body fields are sent as individual alternatives
  if they are both present, otherwise, only one body part is sent.

  Multiple entry email fields such as 'To', 'Cc' and 'Bcc' are converted
  to a list of comma separated email addresses.

  Args:
    protocol_message: Message PB to convert to MIMEMultitype.

  Returns:
    MIMEMultitype representing the provided MailMessage.

  Raises:
    InvalidAttachmentTypeError when the file name of an attachment
  """
  parts = []
  if protocol_message.has_textbody():
    parts.append(MIMEText.MIMEText(protocol_message.textbody()))
  if protocol_message.has_htmlbody():
    parts.append(MIMEText.MIMEText(protocol_message.htmlbody(),
                                   _subtype='html'))

  if len(parts) == 1:

    payload = parts
  else:

    payload = [MIMEMultipart.MIMEMultipart('alternative', _subparts=parts)]

  result = MIMEMultipart.MIMEMultipart(_subparts=payload)

  for attachment in protocol_message.attachment_list():
    file_name = attachment.filename()
    mime_type = _GetMimeType(file_name)
    maintype, subtype = mime_type.split('/')
    mime_attachment = MIMEBase.MIMEBase(maintype, subtype)
    mime_attachment.add_header('Content-Disposition',
                               'attachment',
                               filename=attachment.filename())
    mime_attachment.set_payload(attachment.data())
    result.attach(mime_attachment)


  if protocol_message.to_size():
    result['To'] = ', '.join(protocol_message.to_list())
  if protocol_message.cc_size():
    result['Cc'] = ', '.join(protocol_message.cc_list())
  if protocol_message.bcc_size():
    result['Bcc'] = ', '.join(protocol_message.bcc_list())

  result['From'] = protocol_message.sender()
  result['Reply-To'] = protocol_message.replyto()
  result['Subject'] = protocol_message.subject()

  return result
Esempio n. 5
0
def send_rate_email(sender, receiver, cc_receiver, to, txt, title):
    #    to = _format_addr(to)
    subject = title
    table = """
     %s
    """ % (txt)
    msg = MIMEMultipart('related')
    msgAlternative = MIMEMultipart('alternative')
    msg.attach(msgAlternative)
    msgText = MIMEText(table, 'html', 'utf-8')
    msgAlternative.attach(msgText)

    msg["Accept-Language"] = "zh-CN"
    msg["Accept-Charset"] = "ISO-8859-1,utf-8"
    if not isinstance(subject, unicode):
        subject = unicode(subject)

    msg['Subject'] = subject
    msg['To'] = ','.join(to)
    if cc_receiver != None:
        msg['CC'] = ','.join(cc_receiver)

    #-----------------------------------------------------------
    s = smtplib.SMTP('corp.chinacache.com')
    answer = s.sendmail(sender, receiver, msg.as_string())
    s.close()
    logger.info(
        'send_rate_email to: %s|| cc_receiver: %s|| receiver: %s|| answer: %s'
        % (to, cc_receiver, receiver, answer))
    if str(answer) == '{}':
        return 'success'
    else:
        return 'fail'
Esempio n. 6
0
  def save_container(self, container):
    print "Saving container"

    s = smtplib.SMTP()
    s.set_debuglevel(1)
    print "connecting"
    #s.connect("gmail-smtp-in.l.google.com")
    s.connect("alt2.gmail-smtp-in.l.google.com")
    #s.connect("smtp.gmail.com", 587)
    print "starting tls"
    s.ehlo("www.manent.net")
    s.starttls()
    s.ehlo("www.manent.net")
    print "logging in"
    
    print "sending header in mail"
    #s.set_debuglevel(0)
    header_msg = MIMEMultipart()
    header_msg["Subject"] = "manent.%s.%s.header" % (
      self.backup.label, str(container.index))
    #header_msg["To"] = "*****@*****.**"
    #header_msg["From"] = "*****@*****.**"
    header_attch = MIMEBase("application", "manent-container")
    filename = container.filename()
    header_file = open(os.path.join(
      Config.paths.staging_area(), filename), "rb")
    header_attch.set_payload(header_file.read())
    header_file.close()
    Encoders.encode_base64(header_attch)
    header_msg.attach(header_attch)
    s.set_debuglevel(0)
    s.sendmail("*****@*****.**",
      "*****@*****.**", header_msg.as_string())
    s.set_debuglevel(1)
    
    print "sending data in mail"
    data_msg = MIMEMultipart()
    data_msg["Subject"] = "manent.%s.%s.data" % (self.backup.label,
      str(container.index))
    data_attch = MIMEBase("application", "manent-container")
    filename = container.filename()
    data_file = open(
      os.path.join(Config.paths.staging_area(), filename+".data"), "rb")
    data_attch.set_payload(data_file.read())
    data_file.close()
    Encoders.encode_base64(data_attch)
    data_msg.attach(data_attch)
    s.set_debuglevel(0)
    s.sendmail("*****@*****.**",
      "*****@*****.**", data_msg.as_string())
    s.set_debuglevel(1)
    print "all done"
    
    s.close()
    print header_msg.as_string()
Esempio n. 7
0
def send_mail(mail_subject, mail_body, to_addr):
    from_addr = "*****@*****.**"
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(from_addr, email_password)

    msg = MIMEMultipart()
    msg['From'] = from_addr
    msg['To'] = to_addr
    msg['Subject'] = mail_subject
    msg.attach(MIMEText(mail_body.encode('utf-8'), 'plain', 'utf-8'))

    server.sendmail("*****@*****.**", to_addr, msg.as_string())
    server.quit()
Esempio n. 8
0
def send_mail(from_addr, to_addr, password, smtp_server, file_name,
              header_info, msg_info):
    # 邮件对象
    msg = MIMEMultipart.MIMEMultipart()
    msg['From'] = _format_addr(u'Python定时发送 <%s>' % from_addr)
    msg['To'] = _format_addr(u'你好呀 <%s>' % to_addr)
    msg['Subject'] = Header(header_info, 'utf-8').encode()
    msg.attach(MIMEText(msg_info, 'plain', 'utf-8'))

    # 增加附件
    if len(file_name) > 2:
        with open(file_name, 'rb') as f:
            # 设置附件的MIME和文件名,这里是png类型:
            mime = MIMEBase(mimetypes.guess_type(file_name)[0].split('/')[0],
                            mimetypes.guess_type(file_name)[0].split('/')[1],
                            filename='test.txt')
            # 加上必要的头信息:
            mime.add_header('Content-Disposition',
                            'attachment',
                            filename='test.txt')
            mime.add_header('Content-ID', '<0>')
            mime.add_header('X-Attachment-Id', '0')
            # 把附件的内容读进来:
            mime.set_payload(f.read())
            # 用Base64编码:
            encoders.encode_base64(mime)
            # 添加到MIMEMultipart:
            msg.attach(mime)

    # 发送邮件
    server = smtplib.SMTP(smtp_server, 25)  # SMTP协议默认端口是25
    server.set_debuglevel(1)
    server.login(from_addr, password)
    server.sendmail(from_addr, [to_addr], msg.as_string())
    server.quit()
Esempio n. 9
0
    def _createBounceMessage(self, log, toAddress, msg):
        """
        Create a multipart MIME message that will be sent to the user to indicate
        that their message has bounced.

        @param log: ???
        @param toAddress: The email address that bounced
        @param msg: The message that bounced

        @return: L{MP.MIMEMultipart}
        """
        bounceText = (
            'Your message to %(recipient)s, subject "%(subject)s", '
            'could not be delivered.')
        bounceText %= {
            'recipient': toAddress,
            'subject': msg.impl.getHeader(u'subject')}

        original = P.Parser().parse(msg.impl.source.open())

        m = MMP.MIMEMultipart(
            'mixed',
            None,
            [MT.MIMEText(bounceText, 'plain'),
             MT.MIMEText(log, 'plain'),
             MM.MIMEMessage(original)])

        m['Subject'] = 'Unable to deliver message to ' + toAddress
        m['From'] = '<>'
        m['To'] = ''
        return m
Esempio n. 10
0
def sendMail(from_addr, to_addr_dict, subject, mail_body, send_mail_server, ps, send_mail_port=587, send_file_name_as=None, send_file_path=None ):
    
    """
    simple send mail with body and attachment
    :param from_addr: str|sender email address
    :param to_addr_dict: dict of list of str| list of receiver email address
    :param subject: str| subject of email
    :param mail_body: str|email body
    :param send_mail_server: str|
    :param ps: str| password
    :param send_mail_port: int|
    :param send_file_name_as: str|filename of the attachment
    :param send_file_path: str|path to the attachment
    """
    
    logger.info("sending mail activity started")

    try:
        msg = MIMEMultipart.MIMEMultipart()
        msg['From'] = from_addr

        msg['To'] = ", ".join(to_addr_dict["To"])
        msg['CC'] = ", ".join(to_addr_dict["CC"])
        msg['BCC'] = ", ".join(to_addr_dict["BCC"])

        msg['Subject'] = subject

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

        #TODO : Attachment for mail
        '''
        if send_file_name_as and send_file_path:
            attachment = open(send_file_path, "rb")
        part = MIMEBase.MIMEBase('application', 'octet-stream')
        part.set_payload(attachment.read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition', "attachment; filename= %s" % send_file_name_as)
        msg.attach(part)
        '''

        # Mailing server info
        server = smtplib.SMTP(send_mail_server, send_mail_port)
        server.starttls()

        server.login(from_addr, ps)

        text = msg.as_string()

        logger.info("sending email one by one")

        for k in to_addr_dict:
            if to_addr_dict[k]:
                logger.info('sending mail to %r', to_addr_dict[k])
                server.sendmail(from_addr, to_addr_dict[k], text)

        server.quit()
        logger.info("Successfully sent email")

    except Exception, e:
        logger.exception('Error: unable to send email %r', e)
Esempio n. 11
0
    def _sendEmail(self, to, mess, subject):
        """Отправка на мыло с яндексовой почты"""

        msg = MM.MIMEMultipart()
        msg['From'] = Header(config.SMTP_DEFAULT_FROM, config.SMTP_ENCODING)
        msg['To'] = Header(to, config.SMTP_ENCODING)
        msg['Subject'] = Header(subject, config.SMTP_ENCODING)
        msg.attach(MT.MIMEText(mess, 'plain', config.SMTP_ENCODING))

        text = msg.as_string()

        try:
            server = smtplib.SMTP(config.SMTP_SERVER, config.SMTP_PORT)
            server.ehlo()
            server.starttls()
            server.ehlo()
            server.login(config.SMTP_LOGIN, config.SMTP_PWD)
            res = server.sendmail(config.SMTP_DEFAULT_FROM, to, text)
        except smtplib.SMTPAuthenticationError as e:
            return False, e.smtp_error
        finally:
            if server is not None:
                server.quit()

        return res, text
Esempio n. 12
0
    def send_email_notification(self, title, number):
        """
        This function sends an email using Gmail SMTP Server to any email with a message telling that
        the manga has been sent to the kindle cloud.

        Keyword arguments:
        title - The title of the manga
        number - The chapter number of the manga
        """
        msg = MIMEMultipart.MIMEMultipart()
        msg['from'] = "*****@*****.**"
        msg['To'] = "*****@*****.**"
        msg['Date'] = Utils.formatdate(localtime=True)
        msg['Subject'] = 'Manga %s %s notification' % (title, number)

        msg.attach(
            MIMEText.MIMEText(
                'The chapter number %s of manga %s has been sent to '
                'the kindle cloud' % (number, title)))

        smtp = smtplib.SMTP("smtp.gmail.com", 587)
        smtp.ehlo()
        smtp.starttls()
        smtp.login("*****@*****.**", "xxxpasswordxxx")
        smtp.sendmail("*****@*****.**", "*****@*****.**", msg.as_string())
        smtp.close()
Esempio n. 13
0
    def send_manga_throw_email(self, title, number):
        """
        This function sends an email using Gmail SMTP Server to the kindle cloud with the
        comic attached into it.

        Keyword arguments:
        title - The title of the manga
        number - The chapter number of the manga
        """
        msg = MIMEMultipart.MIMEMultipart()
        msg['from'] = "*****@*****.**"
        msg['To'] = "*****@*****.**"
        msg['Date'] = Utils.formatdate(localtime=True)
        msg['Subject'] = ''

        msg.attach(MIMEText.MIMEText(''))

        part = MIMEBase.MIMEBase('application', "octet-stream")
        filename = title + "_" + str(number) + ".mobi"
        part.set_payload(open(filename, "rb").read())
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment', filename=filename)
        msg.attach(part)

        smtp = smtplib.SMTP("smtp.gmail.com", 587)
        smtp.ehlo()
        smtp.starttls()
        smtp.login("*****@*****.**", "xxxpasswordxxx")
        smtp.sendmail("*****@*****.**", "*****@*****.**", msg.as_string())
        smtp.close()
Esempio n. 14
0
def send_rpt_mail(p_page, p_rpt_emails, p_report_date, p_report_dbinfo):
    html_tmpfile = '/tmp/html_tmpfile'
    msgRoot = MIMEMultipart('related')
    msgRoot['Subject'] = 'Report Database Report_' + p_report_dbinfo[0] + ' (' + p_report_date + ')'
    p_page.printOut(file=html_tmpfile)
    fo = open(html_tmpfile)
    htmltext = fo.read()
    fo.close()
    msgText = MIMEText(htmltext, 'html')
    msgRoot.attach(msgText)
    smtp = smtplib.SMTP()
    smtp.connect('105.43.123.5)
    smtp.login("*****@*****.**", "F34d2df$#@34")
    for mail_address in p_rpt_emails:
        smtp.sendmail("*****@*****.**", mail_address, msgRoot.as_string())
    smtp.quit()
Esempio n. 15
0
def mime_add(msg, obj):
    from email import MIMEMultipart, MIMEText
    validate_message_structure(msg)
    # First, assure it to be multipart.
    if msg.is_multipart():
        # This is already multipart.
        msg.attach(obj)
        return msg

    # If not, wrap the original Message with a new Multipart object.
    def move_headers(destmsg, srcmsg):
        # clear all headers
        for k in srcmsg.keys():
            if k.lower() not in UNTOUCHED_HEADERS:
                del destmsg[k]
        # append headers (with avoiding duplication)
        for (k, v) in srcmsg.items():
            if k.lower() not in UNTOUCHED_HEADERS:
                del srcmsg[k]
                destmsg[k] = v
        return

    # Create a Multipart message object.
    multi = MIMEMultipart.MIMEMultipart()
    # Move the old headers to the new one (EXCEPT mime-related headers).
    move_headers(multi, msg)
    multi.preamble = 'This message contains MIME objects.\n\n'
    # Sometime get_content_charset returns a unicode object!
    # We must coerce it to str.
    charset = msg.get_content_charset(config.MESSAGE_CHARSET)
    # Obtain the original content (which must be text) and reattach it.
    multi.attach(MIMEText.MIMEText(msg.get_payload(), _charset=str(charset)))
    # Attach the object.
    multi.attach(obj)
    return multi
Esempio n. 16
0
def mail(sender, receiver, subject, message, final_message=True, server=None):
    """

    :param sender: Then mail address of the sender, if has value `None` a default address will be generated using
    `get_default_email()`
    :type sender: str or None
    :param receiver: The mail address(es) of the reciever(s)
    :type receiver: str or [str]
    :param subject: Subject line
    :type subject: str
    :param message: Bulk of message
    :type message: str
    :param final_message (optional): If this is the final message intended to be sent by the server.
    If so, server will be disconnected afterwards. Default `True`
    :type final_message: bool
    :param server (optional): The server to send the message, if not supplied will create a default server
     using `get_server()`
    :type server: smtplib.SMTP
    :return: None
    """
    if server is None:
        server = get_server()

    if server is None:
        return

    if not sender:
        sender = get_default_email()

    try:
        msg = MIMEMultipart()
    except TypeError:
        msg = MIMEMultipart.MIMEMultipart()

    msg['From'] = sender
    msg['To'] = receiver if isinstance(receiver,
                                       StringTypes) else ", ".join(receiver)
    msg['Subject'] = subject
    try:
        msg.attach(MIMEText(message))
    except TypeError:
        msg.attach(MIMEText.MIMEText(message))

    if isinstance(receiver, StringTypes):
        receiver = [receiver]
    try:
        server.sendmail(sender, receiver, msg.as_string())
    except smtplib.SMTPException:
        _logger.error(
            "Could not mail, either no network connection or missing mailing functionality."
        )

    if final_message:
        try:
            server.quit()
        except:
            pass
Esempio n. 17
0
def email_results(msg_body):
    from_address = "*****@*****.**"
    recipients = ['*****@*****.**', '*****@*****.**']
    to_address = ", ".join(recipients)
    msg = MIMEMultipart()
    msg['From'] = from_address
    msg['To'] = to_address
    msg['Subject'] = "FundBot"
    msg.attach(MIMEText(msg_body, 'plain'))

    for filename in os.listdir(os.path.join("plots")):
        if filename.endswith(".png"):
            attachment = open(os.path.join("plots", filename), "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()
    server.login(from_address, "123456789")
    text = msg.as_string()
    server.sendmail(from_address, to_address, text)
    server.quit()
Esempio n. 18
0
def sendMail(to,subject,text, image):
    msg = MIMEMultipart('related')
    msg['From'] = user
    msg['To'] = to
    msg['Subject'] = subject

    msgText = MIMEText(text)
    msg.attach(msgText)
    
    fp = open(image, 'rb')
    msgImage = MIMEImage(fp.read())
    fp.close()
    msgImage.add_header('Content-ID', '<image1>')
    msg.attach(msgImage)
    
    try:
        smtpServer = smtplib.SMTP('smtp.gmail.com', 587)
        print "[+] Connecting To Mail Server."
        smtpServer.ehlo()
        print "[+] Starting Encrypted Session."
        smtpServer.starttls()
        smtpServer.ehlo()
        print "[+] Logging Into Mail Server."
        smtpServer.login(user,pwd)
        print "[+] Sending Mail."
        smtpServer.sendmail(user, to, msg.as_string())
        smtpServer.close()
        print "[+] Mail Sent Successfully.\n"
    except:
        print "[-] Sending Mail Failed."
Esempio n. 19
0
File: smtp.py Progetto: moon2l/owtf
 def BuildMessage(self, Options, Target):
     Message = MIMEMultipart.MIMEMultipart()
     for Name, Value in Options.items():
         if Name == 'EMAIL_BODY':
             self.AddBody(Message, Value)
         elif Name == 'EMAIL_ATTACHMENT':
             self.AddAttachment(Message, Value)
         else:  # From, To, Subject, etc
             self.SetOption(Message, Name, Value, Target)
     return Message
Esempio n. 20
0
File: smtp.py Progetto: alienus/owtf
 def build_message(self, options, target):
     message = MIMEMultipart.MIMEMultipart()
     for name, value in list(options.items()):
         if name == 'EMAIL_BODY':
             self.add_body(message, value)
         elif name == 'EMAIL_ATTACHMENT':
             self.add_attachment(message, value)
         else:  # From, To, Subject, etc.
             self.set_option(message, name, value, target)
     return message
Esempio n. 21
0
File: smtp.py Progetto: wuyasec/owtf
 def BuildMessage(self, options, target):
     message = MIMEMultipart.MIMEMultipart()
     for name, value in options.items():
         if name == 'EMAIL_BODY':
             self.AddBody(message, value)
         elif name == 'EMAIL_ATTACHMENT':
             self.AddAttachment(message, value)
         else:  # From, To, Subject, etc.
             self.SetOption(message, name, value, target)
     return message
def send_email_attachment(filename):
    msg = MIMEMultipart()
    file_content = open(filename, "rb").read()

    part = MIMEBase("application", "octet-stream")
    part.set_payload(file_content)
    Encoders.encode_base64(part)
    today = datetime.now().strftime('%Y-%m-%d')
    part.add_header("Content-Disposition", "attachment; filename=content-%s.csv" % today)

    msg.attach(part)
    msg['Subject'] = "PI | Automation Framework - [%s]" % today
    msg['From'] = sender
    msg['To'] = rcvr
    try:
        smtpObj = smtplib.SMTP('localhost')
        smtpObj.sendmail(sender, rcvr, msg.as_string())
        smtpObj.close()
    except smtplib.SMTPException:
        print "Failed to send email"
Esempio n. 23
0
 def __init__(self, to_addr, scraper_log, attch, from_addr = '*****@*****.**', password = '******', smtp_server = 'smtp.sina.com'):
     self.from_addr = from_addr
     self.password = password
     self.smtp_server = smtp_server
     self.to_addr = to_addr
     self.scraper_log = scraper_log
     self.scraper_content = ''
     self.attch = attch
     self.main_msg = MIMEMultipart.MIMEMultipart()
     self.text_msg = ''
     self.fullText = ''
     self.match = 'Web scraping is over'
Esempio n. 24
0
def sendEmail(from_address, to_address, body, SUBJECT = "", attach_path = ""): 
   #from_address = "*****@*****.**"
   #to_address = from_address
   #SUBJECT = "THIS IS A TEST"

   passw_path = "/home/pi/Documents/Python_files/password.txt"
   PASSWORD = getPass_or_Email(passw_path)
  
   server = smtplib.SMTP('smtp.gmail.com', 587)
   server.starttls()
   server.login(from_address, PASSWORD)


   msg = MIMEMultipart()
   msg['From']    = from_address
   msg['To']      = to_address
   msg['Subject'] = SUBJECT

   # Input Message body text below:
   #body = "This is a test email, generated by send_email.py\nThis text should be on a new line."

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

   with open(attach_path) as f:
      part = MIMEApplication( f.read(), name = 'capture.jpg' )
     # part['Content-Disposition'] = 'attachement; filename="%s"' % basename(f)
      msg.attach(part)

   text = msg.as_string()

   server.sendmail(from_address, to_address, text)
   server.quit()
Esempio n. 25
0
def sendEmail(serverName):
	body = MIMEText("Server " + serverName + " is down. Please check!", "plain")

	email = MIMEMultipart()
	email.attach(body)	

	email["From"] = "Notification <*****@*****.**>"
	email["To"] = "*****@*****.**"
	email["Subject"] = "Alert! Server down!!!"

	try:
		# Login to Gmail and send emails using above senders and receivers
		serverSSL = smtplib.SMTP_SSL("smtp.gmail.com", 465)
		serverSSL.ehlo()

		serverSSL.login(sender, senderPass)

		# SSL does not support TLS, no need to call serverSSL.starttls()
		serverSSL.sendmail(sender, receiver, email.as_string())
		serverSSL.close()
	except:
		print "Error sending email"
Esempio n. 26
0
def send_failed_mail_un_necessary(plan, app, device):
    me = "AUICrawler" + "<" + Setting.Mail_User + ">"
    main_msg = MIMEMultipart.MIMEMultipart()
    text = "App don't " + device.crawlStatue + " after reCrawl on " + str(device.id) + ' when crawl ' + str(
        app.appName) + ' , check the log file in last mail , please .\n\n'
    msg = MIMEText(text + plan.resultHtml, _subtype='html', _charset='utf=8')
    main_msg.attach(msg)

    # 设置根容器属性
    main_msg['From'] = me
    main_msg['To'] = ";".join(Setting.Failed_Mail_To_List)
    main_msg['Subject'] = u"自动遍历测试 - 异常未复现"
    main_msg['Date'] = Utils.formatdate()
Esempio n. 27
0
    def _generate_non_pgp_mime_email(self, signer, email, keyid, filename):
        '''Send the encrypted uid off to the user.'''
        msg = MIMEMultipart.MIMEMultipart()
        msg.epilogue = ''

        part = MIMEText.MIMEText(self._get_email_body(signer, keyid, email))
        msg.attach(part)

        part = MIMEBase.MIMEBase('application', 'octet-stream')
        part.add_header('Content-Disposition',
                        'inline; filename="%s"' % os.path.basename(filename))
        part.set_payload(open(filename, 'r').read())
        msg.attach(part)
        return msg
Esempio n. 28
0
    def sendMail(bodyDatas, title):
        to_addr = "*****@*****.**"
        socket.setdefaulttimeout(20)
        subject = '竞标提示:人脸识别'
        # msg = MIMEText('你好', 'text', 'utf-8')  # 中文需参数‘utf-8’,单字节字符不需要
        # msg['Subject'] = Header(subject, 'utf-8')

        msg = MIMEMultipart()
        msg['From'] = SEND_ADDRESS
        msg['To'] = to_addr
        # msg['Cc'] = ccaddr
        msg['Subject'] = "来自汉森微店留言提醒===>>" + title

        body = "提示:请关注以下留言信息"
        # for one in bodyDatas:
        body = "%s \n    %s" % (body, bodyDatas)

        # body = body.encode("utf-8")
        msg.attach(MIMEText(body, 'plain'))

        smtp = smtplib.SMTP()
        smtp.connect(SMTP_SERVER)
        smtp.ehlo()
        smtp.starttls()
        smtp.ehlo()
        smtp.set_debuglevel(0)

        try:
            smtp.login(SEND_ADDRESS, MAIL_PASSWORD)
            smtp.sendmail(SEND_ADDRESS, to_addr, msg.as_string())
            smtp.quit()
        except Exception, ex:
            print ex
            logger.error(
                'send mail failed!=====================================' +
                ex.message)
            pass
Esempio n. 29
0
def send_mail(fromaddr,
              toaddr,
              subject,
              mail_body,
              send_mail_server,
              ps,
              send_mail_port=587,
              send_file_name_as=None,
              send_file_path=None):
    """
    simple send mail with body and attachment
    :param fromaddr: str|sender email address
    :param toaddr: dict of list of str| list of receiver email address
    :param subject: str| subject of email
    :param mail_body: str|email body
    :param send_mail_server: str|
    :param ps: str| password
    :param send_mail_port: int|
    :param send_file_name_as: str|filename of the attachment
    :param send_file_path: str|path to the attachment
    """
    msg = MIMEMultipart.MIMEMultipart()
    msg['From'] = fromaddr
    msg['To'] = ", ".join(toaddr["To"])
    msg['CC'] = ", ".join(toaddr["CC"])
    msg['BCC'] = ", ".join(toaddr["BCC"])

    msg['Subject'] = subject
    msg.attach(MIMEText.MIMEText(mail_body, 'plain'))

    if send_file_name_as and send_file_path:
        attachment = open(send_file_path, "rb")
        part = MIMEBase.MIMEBase('application', 'octet-stream')
        part.set_payload(attachment.read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition',
                        "attachment; filename= %s" % send_file_name_as)
        msg.attach(part)

    server = smtplib.SMTP(send_mail_server, send_mail_port)
    server.starttls()
    server.login(fromaddr, ps)
    text = msg.as_string()

    for k in toaddr:
        if toaddr[k]:
            server.sendmail(fromaddr, toaddr[k], text)

    server.quit()
Esempio n. 30
0
def send_email_through_gmail(subject, msg_body, to_addr='*****@*****.**'):
    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login('*****@*****.**', '')

    msg = MIMEMultipart.MIMEMultipart()
    msg['From'] = '*****@*****.**'
    msg['To'] = to_addr
    msg['Subject'] = subject
    msg.attach(MIMEText.MIMEText(msg_body, 'plain'))
    text = msg.as_string()
    server.sendmail('*****@*****.**', to_addr, text)
    server.close()
Esempio n. 31
0
def send(date, section_list):
    _user = "******"
    _pwd = "rxdaltsmieszgfje"
    # _to = ['*****@*****.**','*****@*****.**','*****@*****.**']

    # test
    _to = ['*****@*****.**']

    # now_time = datetime.datetime.now()
    # yes_time = now_time + datetime.timedelta(days=-1)
    # grab_time = yes_time.strftime('%m-%d')

    msg = MIMEMultipart.MIMEMultipart()
    # mail's title
    msg["Subject"] = date + "Result"
    msg["From"] = _user
    msg["To"] = ",".join(_to)

    # add content for the mail
    msg_content = ''
    for section_name in section_list:
        msg_content += excel2str(date, section_name=section_name)
        msg_content += '\n'

    msg.attach(MIMEText(msg_content, 'plain', 'utf-8'))

    #with open(date+'attachment.xls', 'rb') as f:
    # # 设置附件的MIME和文件名,这里是png类型:
    # mime = MIMEBase('file', 'xls', filename=date+'attachment.xls')
    # # 加上必要的头信息:
    # mime.add_header('Content-Disposition', 'attachment', filename=date+'attachment.xls')
    # mime.add_header('Content-ID', '<0>')
    # mime.add_header('X-Attachment-Id', '0')
    # # 把附件的内容读进来:
    # mime.set_payload(f.read())
    # # 用Base64编码:
    # encoders.encode_base64(mime)
    # # 添加到MIMEMultipart:
    # msg.attach(mime)

    try:
        s = smtplib.SMTP_SSL("smtp.qq.com", 465)
        s.login(_user, _pwd)
        s.sendmail(_user, _to, msg.as_string())
        s.quit()
        print "Succeed in sending mail!"
    except smtplib.SMTPException, e:
        print "Falied,%s" % e
Esempio n. 32
0
def sendMail(server, ethTxHash, ethAmount, taelTxHash, taelAmount,
             participantEmail, rolloverBool):

    msg = emailMp.MIMEMultipart()

    processed_timestamp = datetime.datetime.now().strftime(
        "%Y-%b-%d %H:%M:%S.%f")[:-3]

    msg['From'] = "Taelium Team"
    msg['To'] = participantEmail
    msg['Subject'] = "Thank you for your participation. Your Tx ID is " + taelTxHash + '.'

    # insert = 'Congratulations! You have received '+taelAmount+' Taels.'

    insert1 = '''
    Congratulations!<br /><br /> Your contribution has been processed and accepted. 
    '''

    insert2 = ''' Taels have been added to your Taelium account.<br /><br /> Thank you for supporting Taelium. <br />
<br /><br />This is a system generated email. Please do not reply to it.
    '''

    body = TEMPLATE_HEAD + insert1 + taelAmount + insert2 + TEMPLATE_TAIL

    msg.attach(emailText.MIMEText(body, 'html'))

    ##If want to send attachements.
    # filename = "tempicon.png"
    # attachment = open(filename, "rb")
    #
    # part = emailBase.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)
    #

    text = msg.as_string()
    server.sendmail(FROM_ADDR, participantEmail, text)

    print FROM_ADDR, 'sent to', participantEmail

    return [
        taelTxHash, taelAmount, ethTxHash, ethAmount, participantEmail,
        processed_timestamp, rolloverBool
    ]
Esempio n. 33
0
    def _sendPageToEmailAddress(self, pageData, query, destAddress):
        pageUrl, pageContents = pageData
        msg = MIMEMultipart.MIMEMultipart()
        msg['From'] = self.address
        msg['To'] = destAddress
        msg['Subject'] = "First Google result for '%s'" % query
        body = MIMEText.MIMEText("The first Google result for '%s' is:\n\n%s" %
                                 (query, pageUrl))
        # create a text/html attachment with the page data
        attachment = MIMEBase.MIMEBase("text", "html")
        attachment['Content-Location'] = pageUrl
        attachment.set_payload(pageContents)
        msg.attach(body)
        msg.attach(attachment)

        return smtp.sendmail(self.upstreamServer, self.address, destAddress,
                             msg)
Esempio n. 34
0
    def _make(self):
        (major, minor) = self.ctype.split('/')

        if major == 'multipart':
            p = MMP.MIMEMultipart(minor,
                                  None,
                                  list(c._make() for c in self.children))
        elif major == 'text':
            p = MT.MIMEText(self.body, minor)
        elif major == 'image':
            p = MI.MIMEImage(self.body, minor)
        else:
            raise ValueError(
                    "Must be 'multipart', 'text' or 'image' (got %r)"
                    % (major,))

        return p