Python smtplib.SMTP Examples

The following are 30 code examples of smtplib.SMTP(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module smtplib , or try the search function .
Example #1
Source File: util.py    From openSUSE-release-tools with GNU General Public License v2.0 11 votes vote down vote up
def mail_send_with_details(relay, sender, subject, to, text, xmailer=None, followup_to=None, dry=True):
    import smtplib
    from email.mime.text import MIMEText
    import email.utils
    msg = MIMEText(text, _charset='UTF-8')
    msg['Subject'] = subject
    msg['Message-ID'] = email.utils.make_msgid()
    msg['Date'] = email.utils.formatdate(localtime=1)
    msg['From'] = sender
    msg['To'] = to
    if followup_to:
        msg['Mail-Followup-To'] = followup_to
    if xmailer:
        msg.add_header('X-Mailer', xmailer)
    msg.add_header('Precedence', 'bulk')
    if dry:
        logger.debug(msg.as_string())
        return
    logger.info("%s: %s", msg['To'], msg['Subject'])
    s = smtplib.SMTP(relay)
    s.sendmail(msg['From'], {msg['To'], sender }, msg.as_string())
    s.quit() 
Example #2
Source File: qqbot.py    From QBotWebWrap with GNU General Public License v3.0 10 votes vote down vote up
def sendfailmail():
    global QQUserName, MyUIN
    try:
        SUBJECT = 'QQ挂机下线提醒: '+str(QQUserName)+'[QQ号:'+str(MyUIN)+']'
        TO = [sendtomail]
        msg = MIMEMultipart('alternative')
        msg['Subject'] = Header(SUBJECT, 'utf-8')
        msg['From'] = mailsig+'<'+mailuser+'>'
        msg['To'] = ', '.join(TO)
        part = MIMEText("Fatal error occured. Please restart the program and login again!", 'plain', 'utf-8')
        msg.attach(part)
        server = smtplib.SMTP(mailserver, 25)
        server.login(mailuser, mailpass)
        server.login(mailuser, mailpass)
        server.sendmail(mailuser, TO, msg.as_string())
        server.quit()
        return True
    except Exception , e:
        logging.error("发送程序错误邮件失败:"+str(e))
        return False 
Example #3
Source File: utils.py    From ffplayout-engine with GNU General Public License v3.0 8 votes vote down vote up
def send_mail(self, msg):
        if _mail.recip:
            # write message to temp file for rate limit
            with open(self.temp_msg, 'w+') as f:
                f.write(msg)

            self.current_time()

            message = MIMEMultipart()
            message['From'] = _mail.s_addr
            message['To'] = _mail.recip
            message['Subject'] = _mail.subject
            message['Date'] = formatdate(localtime=True)
            message.attach(MIMEText('{} {}'.format(self.time, msg), 'plain'))
            text = message.as_string()

            try:
                server = smtplib.SMTP(_mail.server, _mail.port)
            except socket.error as err:
                playout_logger.error(err)
                server = None

            if server is not None:
                server.starttls()
                try:
                    login = server.login(_mail.s_addr, _mail.s_pass)
                except smtplib.SMTPAuthenticationError as serr:
                    playout_logger.error(serr)
                    login = None

                if login is not None:
                    server.sendmail(_mail.s_addr, _mail.recip, text)
                    server.quit() 
Example #4
Source File: qqbot.py    From QBotWebWrap with GNU General Public License v3.0 7 votes vote down vote up
def sendfailmail():
    try:
        SUBJECT = 'QQ小黄鸡下线提醒'
        TO = [sendtomail]
        msg = MIMEMultipart('alternative')
        msg['Subject'] = Header(SUBJECT, 'utf-8')
        msg['From'] = mailsig+'<'+mailuser+'>'
        msg['To'] = ', '.join(TO)
        part = MIMEText("Fatal error occured. Please go to the website and login again!", 'plain', 'utf-8')
        msg.attach(part)
        server = smtplib.SMTP(mailserver, 25)
        server.login(mailuser, mailpass)
        server.login(mailuser, mailpass)
        server.sendmail(mailuser, TO, msg.as_string())
        server.quit()
        return True
    except Exception , e:
        logging.error("发送程序错误邮件失败:"+str(e))
        return False 
Example #5
Source File: watch.py    From Stockeye with MIT License 7 votes vote down vote up
def sendEmail(subject, body, credentials):    
    self = credentials[0]
    password = credentials[1]    
    fromAddr = credentials[2]
    toAddr = credentials[3]   
    msg = MIMEMultipart()
    msg['From'] = fromAddr
    msg['To'] = toAddr
    msg['Subject'] = subject   
    msgText = MIMEText(body, 'html', 'UTF-8')
    msg.attach(msgText)
    server = SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(self, password)
    text = msg.as_string()
    server.sendmail(fromAddr, toAddr, text)
    server.quit()

# --- Scraping Methods --------------------------------------------------------- 
Example #6
Source File: users.py    From cascade-server with Apache License 2.0 7 votes vote down vote up
def send_reset_email(self):
        expires = datetime.datetime.now() + reset_password_timeout
        url = self.generate_reset_link()
        body = ("A password reset for {} has been requested.\r\n".format(self.username),
                "Navigate to {} to complete reset.".format(url),
                "Expires on {}".format(expires.isoformat())
                )
        message = MIMEText('\r\n'.join(body))
        message['Subject'] = "Password Reset Link for CASCADE on {}".format(settings.load()['server']['hostname'])
        message['From'] = 'cascade@' + settings.load()['server']['hostname']
        message['To'] = self.email

        server = smtplib.SMTP(settings.load()['links']['smtp'])
        server.set_debuglevel(1)
        server.sendmail(message['From'], [self.email], message.as_string())
        server.quit() 
Example #7
Source File: util.py    From openSUSE-release-tools with GNU General Public License v2.0 7 votes vote down vote up
def mail_send_with_details(relay, sender, subject, to, text, xmailer=None, followup_to=None, dry=True):
    import smtplib
    from email.mime.text import MIMEText
    import email.utils
    msg = MIMEText(text, _charset='UTF-8')
    msg['Subject'] = subject
    msg['Message-ID'] = email.utils.make_msgid()
    msg['Date'] = email.utils.formatdate(localtime=1)
    msg['From'] = sender
    msg['To'] = to
    if followup_to:
        msg['Mail-Followup-To'] = followup_to
    if xmailer:
        msg.add_header('X-Mailer', xmailer)
    msg.add_header('Precedence', 'bulk')
    if dry:
        logger.debug(msg.as_string())
        return
    logger.info("%s: %s", msg['To'], msg['Subject'])
    s = smtplib.SMTP(relay)
    s.sendmail(msg['From'], {msg['To'], sender }, msg.as_string())
    s.quit() 
Example #8
Source File: send_email_with_python.py    From autopython with GNU General Public License v3.0 7 votes vote down vote up
def send_mail(to_email,message):
# 定义邮件发送
# Define send_mail() function
	smtp_host = 'smtp.xxx.com'
	# 发件箱服务器
	# Outbox Server
	from_email = 'from_email@xxx.com'
	# 发件邮箱
	# from_email
	passwd = 'xxxxxx'
	# 发件邮箱密码
	# from_email_password
	msg = MIMEText(message,'plain','utf-8')
	msg['Subject'] = Header(u'Email Subject','utf-8').encode()
	# 邮件主题
	# Email Subject
	smtp_server = smtplib.SMTP(smtp_host,25)
	# 发件服务器端口
	# Outbox Server Port
	smtp_server.login(from_email,passwd)
	smtp_server.sendmail(from_email,[to_email],msg.as_string())
	smtp_server.quit() 
Example #9
Source File: qqbot.py    From QBotWebWrap with GNU General Public License v3.0 7 votes vote down vote up
def sendfailmail():
    try:
        SUBJECT = 'QQ点赞机下线提醒'
        TO = [sendtomail]
        msg = MIMEMultipart('alternative')
        msg['Subject'] = Header(SUBJECT, 'utf-8')
        msg['From'] = mailsig+'<'+mailuser+'>'
        msg['To'] = ', '.join(TO)
        part = MIMEText("Fatal error occured. Please go to the website and login again!", 'plain', 'utf-8')
        msg.attach(part)
        server = smtplib.SMTP(mailserver, 25)
        server.login(mailuser, mailpass)
        server.login(mailuser, mailpass)
        server.sendmail(mailuser, TO, msg.as_string())
        server.quit()
        return True
    except Exception , e:
        logging.error("发送程序错误邮件失败:"+str(e))
        return False 
Example #10
Source File: qqbot.py    From QBotWebWrap with GNU General Public License v3.0 7 votes vote down vote up
def smtpmail(self,SUBJECT):
        try:
            TO = [sendtomail]
            msg = MIMEMultipart('alternative')
            msg['Subject'] = Header(SUBJECT, 'utf-8')
            msg['From'] = mailsig+'<'+mailuser+'>'
            msg['To'] = ', '.join(TO)
            part = MIMEText(self.content, 'plain', 'utf-8')
            msg.attach(part)        
            server = smtplib.SMTP(mailserver, 25)
            server.login(mailuser, mailpass)
            server.login(mailuser, mailpass)
            server.sendmail(mailuser, TO, msg.as_string())
            server.quit()
            return True
        except Exception, e:
            logging.error("error sending msg:"+str(e))
            return False 
Example #11
Source File: mailer.py    From SecPi with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, id, params):
		super(Mailer, self).__init__(id, params)
		
		try:
			# SMTP Server config + data dir
			self.data_dir = params.get("data_dir", "/var/tmp/secpi/alarms")
			self.smtp_address = params["smtp_address"]
			self.smtp_port = int(params["smtp_port"])
			self.smtp_user = params["smtp_user"]
			self.smtp_pass = params["smtp_pass"]
			self.smtp_security = params["smtp_security"]
		except KeyError as ke: # if config parameters are missing
			logging.error("Mailer: Wasn't able to initialize the notifier, it seems there is a config parameter missing: %s" % ke)
			self.corrupted = True
			return
		except ValueError as ve: # if one configuration parameter can't be parsed as int
			logging.error("Mailer: Wasn't able to initialize the notifier, please check your configuration: %s" % ve)
			self.corrupted = True
			return

		logging.info("Mailer: Notifier initialized") 
Example #12
Source File: email_handler.py    From app with MIT License 6 votes vote down vote up
def handle_DATA(self, server, session, envelope: Envelope):
        LOG.debug(
            "===>> New message, mail from %s, rctp tos %s ",
            envelope.mail_from,
            envelope.rcpt_tos,
        )

        if POSTFIX_SUBMISSION_TLS:
            smtp = SMTP(POSTFIX_SERVER, 587)
            smtp.starttls()
        else:
            smtp = SMTP(POSTFIX_SERVER, POSTFIX_PORT or 25)

        app = new_app()
        with app.app_context():
            return handle(envelope, smtp) 
Example #13
Source File: cyphermain.py    From Cypher with GNU General Public License v3.0 6 votes vote down vote up
def send_Key_SMTP():
	ts = datetime.datetime.now()
	SERVER = "smtp.gmail.com" 		
	PORT = 587 						
	USER= "address@gmail.com"		# Specify Username Here 
	PASS= "prettyflypassword"	    # Specify Password Here
	FROM = USER
	TO = ["address@gmail.com"] 		
	SUBJECT = "Ransomware data: "+str(ts)
	MESSAGE = """\Client ID: %s Decryption Key: %s """ % (ID, exKey)
	message = """\ From: %s To: %s Subject: %s %s """ % (FROM, ", ".join(TO), SUBJECT, MESSAGE)
	try:              
		server = smtplib.SMTP()
		server.connect(SERVER, PORT)
		server.starttls()
		server.login(USER, PASS)
		server.sendmail(FROM, TO, message)
		server.quit()
	except Exception as e:
		# print e
		pass 
Example #14
Source File: handlers.py    From jawfish with MIT License 6 votes vote down vote up
def emit(self, record):
        """
        Emit a record.

        Format the record and send it to the specified addressees.
        """
        try:
            import smtplib
            from email.utils import formatdate
            port = self.mailport
            if not port:
                port = smtplib.SMTP_PORT
            smtp = smtplib.SMTP(self.mailhost, port, timeout=self.timeout)
            msg = self.format(record)
            msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % (
                            self.fromaddr,
                            ",".join(self.toaddrs),
                            self.getSubject(record),
                            formatdate(), msg)
            if self.username:
                if self.secure is not None:
                    smtp.ehlo()
                    smtp.starttls(*self.secure)
                    smtp.ehlo()
                smtp.login(self.username, self.password)
            smtp.sendmail(self.fromaddr, self.toaddrs, msg)
            smtp.quit()
        except (KeyboardInterrupt, SystemExit): #pragma: no cover
            raise
        except:
            self.handleError(record) 
Example #15
Source File: mergeable.py    From buildbot-infra with MIT License 6 votes vote down vote up
def main():
    r = requests.get(
        'https://api.github.com/repos/buildbot/buildbot/issues?labels=merge me'
    )
    body = ["%(html_url)s - %(title)s" % pr for pr in r.json()]
    if not body:
        return

    body = "Mergeable pull requests:\n\n" + "\n".join(body)

    smtp = smtplib.SMTP('localhost')
    smtp.sendmail(FROM, RECIPIENT, """\
Subject: Mergeable Buildbot pull requests
From: %s
To: %s

%s""" % (FROM, RECIPIENT, body)) 
Example #16
Source File: BotDigger.py    From BotDigger with GNU General Public License v3.0 6 votes vote down vote up
def sendEmail(emailContents, receiver):
	SERVER = "localhost"
	FROM = "admin@botdiggertest.com"
	TO = list()
	TO.append(receiver)
	#TO = ["botdiggeradmin@test.com"] # must be a list
	SUBJECT = "BotDigger Notice"
	TEXT = emailContents
	message = """\From: %s\nTo: %s\nSubject: %s\n\n%s""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
	try:
		server = smtplib.SMTP(SERVER)
		server.sendmail(FROM, TO, message)
		server.quit()
		print "Successfully sent email"
	except:
		print "Error: unable to send email" 
Example #17
Source File: qqbot.py    From QBotWebWrap with GNU General Public License v3.0 6 votes vote down vote up
def smtpmail(self,subinfo):
        try:
            SUBJECT = '来自 '+subinfo+'的留言'
            TO = [sendtomail]
            msg = MIMEMultipart('alternative')
            msg['Subject'] = Header(SUBJECT, 'utf-8')
            msg['From'] = mailsig+'<'+mailuser+'>'
            msg['To'] = ', '.join(TO)
            part = MIMEText(self.content, 'plain', 'utf-8')
            msg.attach(part)        
            server = smtplib.SMTP(mailserver, 25)
            server.login(mailuser, mailpass)
            server.login(mailuser, mailpass)
            server.sendmail(mailuser, TO, msg.as_string())
            server.quit()
            return True
        except Exception, e:
            logging.error("error sending msg:"+str(e))
            return False 
Example #18
Source File: mailer.py    From Expert-Python-Programming_Second-Edition with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def send(
    sender, to,
    subject='None',
    body='None',
    server='localhost'
):
    """sends a message."""
    message = email.message.Message()
    message['To'] = to
    message['From'] = sender
    message['Subject'] = subject
    message.set_payload(body)

    server = smtplib.SMTP(server)
    try:
        return server.sendmail(sender, to, message.as_string())
    finally:
        server.quit() 
Example #19
Source File: mailer.py    From Expert-Python-Programming_Second-Edition with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def send(
    sender, to,
    subject='None',
    body='None',
    server='localhost'
):
    """sends a message."""
    message = email.message.Message()
    message['To'] = to
    message['From'] = sender
    message['Subject'] = subject
    message.set_payload(body)

    server = smtplib.SMTP(server)
    try:
        return server.sendmail(sender, to, message.as_string())
    finally:
        server.quit() 
Example #20
Source File: reporter.py    From mishkal with GNU General Public License v3.0 6 votes vote down vote up
def report(self, exc_data):
        msg = self.assemble_email(exc_data)
        server = smtplib.SMTP(self.smtp_server)
        if self.smtp_use_tls:
            server.ehlo()
            server.starttls()
            server.ehlo()
        if self.smtp_username and self.smtp_password:
            server.login(self.smtp_username, self.smtp_password)
        server.sendmail(self.from_address,
                        self.to_addresses, msg.as_string())
        try:
            server.quit()
        except sslerror:
            # sslerror is raised in tls connections on closing sometimes
            pass 
Example #21
Source File: mailer.py    From Expert-Python-Programming_Second-Edition with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def send(
    sender, to,
    subject='None',
    body='None',
    server='localhost'
):
    """sends a message."""
    message = email.message.Message()
    message['To'] = to
    message['From'] = sender
    message['Subject'] = subject
    message.set_payload(body)

    server = smtplib.SMTP(server)
    try:
        return server.sendmail(sender, to, message.as_string())
    finally:
        server.quit() 
Example #22
Source File: mailer.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def server_ssh_connect(self):
		"""
		Connect to the remote SMTP server over SSH and configure port forwarding
		with :py:class:`.SSHTCPForwarder` for tunneling SMTP traffic.

		:return: The connection status as one of the :py:class:`.ConnectionErrorReason` constants.
		"""
		server = smoke_zephyr.utilities.parse_server(self.config['ssh_server'], 22)
		username = self.config['ssh_username']
		password = self.config['ssh_password']
		remote_server = smoke_zephyr.utilities.parse_server(self.config['smtp_server'], 25)
		try:
			self._ssh_forwarder = SSHTCPForwarder(
				server,
				username,
				password,
				remote_server,
				private_key=self.config.get('ssh_preferred_key'),
				missing_host_key_policy=ssh_host_key.MissingHostKeyPolicy(self.application)
			)
			self._ssh_forwarder.start()
		except errors.KingPhisherAbortError as error:
			self.logger.info("ssh connection aborted ({0})".format(error.message))
		except paramiko.AuthenticationException:
			self.logger.warning('failed to authenticate to the remote ssh server')
			return ConnectionErrorReason.ERROR_AUTHENTICATION_FAILED
		except paramiko.SSHException as error:
			self.logger.warning("failed with: {0!r}".format(error))
		except socket.timeout:
			self.logger.warning('the connection to the ssh server timed out')
		except Exception:
			self.logger.warning('failed to connect to the remote ssh server', exc_info=True)
		else:
			self.smtp_server = self._ssh_forwarder.local_server
			return ConnectionErrorReason.SUCCESS
		return ConnectionErrorReason.ERROR_UNKNOWN 
Example #23
Source File: 4_generate_email.py    From deep-learning-note with MIT License 5 votes vote down vote up
def sendMsg(fr, to, msg):
    s = SMTP('smtp.gmail.com')
    s.starttls()
    s.login(MAILBOX + '@gmail.com', PASSWD)
    errs = s.sendmail(fr, to ,msg)
    assert len(errs) == 0, errs #not in book
    s.quit() 
Example #24
Source File: mailer.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def server_smtp_disconnect(self):
		"""Clean up and close the connection to the remote SMTP server."""
		if self.smtp_connection:
			self.logger.debug('closing the connection to the SMTP server')
			try:
				self.smtp_connection.quit()
			except smtplib.SMTPServerDisconnected:
				pass
			self.smtp_connection = None
			self.tab_notify_status('Disconnected from the SMTP server') 
Example #25
Source File: fixture.py    From mishkal with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, server):
        import warnings
        warnings.warn(
            'Dummy_smtplib is not maintained and is deprecated',
            DeprecationWarning, 2)
        assert not self.existing, (
            "smtplib.SMTP() called again before Dummy_smtplib.existing.reset() "
            "called.")
        self.server = server
        self.open = True
        self.__class__.existing = self 
Example #26
Source File: fixture.py    From mishkal with GNU General Public License v3.0 5 votes vote down vote up
def install(cls):
        smtplib.SMTP = cls 
Example #27
Source File: fixture.py    From mishkal with GNU General Public License v3.0 5 votes vote down vote up
def reset(self):
        assert not self.open, (
            "SMTP connection not quit")
        self.__class__.existing = None 
Example #28
Source File: device_email.py    From selene-backend with GNU Affero General Public License v3.0 5 votes vote down vote up
def _send_email(self, message: EmailMessage):
        email_client = self.config.get('EMAIL_CLIENT')
        if email_client is None:
            host = os.environ['EMAIL_SERVICE_HOST']
            port = os.environ['EMAIL_SERVICE_PORT']
            user = os.environ['EMAIL_SERVICE_USER']
            password = os.environ['EMAIL_SERVICE_PASSWORD']
            email_client = smtplib.SMTP(host, port)
            email_client.login(user, password)
        email_client.send_message(message)
        email_client.quit() 
Example #29
Source File: connection.py    From insightconnect-plugins with MIT License 5 votes vote down vote up
def get(self):
        params = self.params
        self.logger.info("Connecting to %s:%d", params['host'], params['port'])
        self.client = SMTP(params['host'], params['port'], timeout=60)
        self.client.ehlo()
        if params.get('use_ssl'):
            self.client.starttls()

        if params.get('credentials').get('username') and params.get('credentials').get('password'):
            self.client.login(params.get('credentials').get('username'), params.get('credentials').get('password'))

        return self.client 
Example #30
Source File: sms.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_smtp_servers(domain):
	"""
	Get the SMTP servers for the specified domain by querying their MX records.

	:param str domain: The domain to look up the MX records for.
	:return: The smtp servers for the specified domain.
	:rtype: list
	"""
	mx_records = dns.resolver.query(domain, 'MX')
	return [str(r.exchange).rstrip('.') for r in mx_records]