我们从Python开源项目中,提取了以下41个代码示例,用于说明如何使用smtplib.SMTP。
def _deliver(self, mailfrom, rcpttos, data): import smtplib refused = {} try: s = smtplib.SMTP() s.connect(self._remoteaddr[0], self._remoteaddr[1]) try: refused = s.sendmail(mailfrom, rcpttos, data) finally: s.quit() except smtplib.SMTPRecipientsRefused, e: print >> DEBUGSTREAM, 'got SMTPRecipientsRefused' refused = e.recipients except (socket.error, smtplib.SMTPException), e: print >> DEBUGSTREAM, 'got', e.__class__ # All recipients were refused. If the exception had an associated # error code, use it. Otherwise,fake it with a non-triggering # exception code. errcode = getattr(e, 'smtp_code', -1) errmsg = getattr(e, 'smtp_error', 'ignore') for r in rcpttos: refused[r] = (errcode, errmsg) return refused
def mail(self): gonderen = "sender e-mail" pswd = "sender e-mail passwd" alici = "receiver e mail " cc = "if you need add cc e-mail " body=self.mesaj print(self.mesaj) try: server = smtplib.SMTP("smtp.live.com", 587) server.starttls() server.login(gonderen, pswd) server.sendmail(gonderen,[alici,cc],body) server.close() print("mail gönderildi") except smtplib.SMTPException as e: print(str(e))
def send_email(subject, msg): import smtplib message = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s\r\n" % (config.EMAIL_HOST_USER, ", ".join(config.EMAIL_RECEIVER), subject, msg) try: smtpserver = smtplib.SMTP(config.EMAIL_HOST) smtpserver.set_debuglevel(0) smtpserver.ehlo() smtpserver.starttls() smtpserver.ehlo smtpserver.login(config.EMAIL_HOST_USER, config.EMAIL_HOST_PASSWORD) smtpserver.sendmail(config.EMAIL_HOST_USER, config.EMAIL_RECEIVER, message) smtpserver.quit() smtpserver.close() logging.info("send mail success") except: logging.error("send mail failed") traceback.print_exc()
def send_email(subject, text, to_addr_list=DEFAULT_EMAIL_LIST): body = string.join(('From: %s' % SENDING_ADDRESS, 'To: %s' % to_addr_list, 'Subject: %s' % subject, '', text), '\r\n') try: server = smtplib.SMTP('smtp.gmail.com:587') # NOTE: This is the GMAIL SSL port. server.ehlo() # this line was not required in a previous working version server.starttls() server.login(SENDING_ADDRESS, 'gmail_password') server.sendmail(SENDING_ADDRESS, to_addr_list, body) server.quit() print "Email sent successfully!" except: return "Email failed to send!"
def init_server(self): self.logger.info("Initializing SMTP/IMAP servers.") # PySMS at minimum uses smtp server try: if self.ssl: self.smtp = smtplib.SMTP_SSL(self.smtp_server, self.smtp_port) else: self.smtp = smtplib.SMTP(self.smtp_server, self.smtp_port) self.smtp.starttls() self.smtp.login(self.address, self.password) except smtplib.SMTPException: raise PySMSException("Unable to start smtp server, please check credentials.") # If responding functionality is enabled if self.imap_server: try: if self.ssl: self.imap = imaplib.IMAP4_SSL(self.imap_server) else: self.imap = imaplib.IMAP4(self.imap_server) r, data = self.imap.login(self.address, self.password) if r == "OK": r, data = self.imap.select(self.imap_mailbox) if r != "OK": raise PySMSException("Unable to select mailbox: {0}".format(self.imap_mailbox)) else: raise PySMSException("Unable to login to IMAP server with given credentials.") except imaplib.IMAP4.error: raise PySMSException("Unable to start IMAP server, please check address and SSL/TLS settings.")
def rolling_restart(service_rr): print service_rr try: #if service_rr.name.lower() in ['hive', 'hue', 'oozie', 'spark']: # raise AttributeError("Rolling Restart is not available for '%s' " % service.name.lower()) batch_size = raw_input("Number of worker roles to restart together in a batch \n") fail_count_threshold = raw_input("Stop rolling restart if more than this number of worker batches fail \n") options = ["true", "false"] # options for stale config stale_config_only = select_from_items('option to Restart roles on nodes with stale config?(Default is false) \n', options) # Needs to be a user selection rr_command = service_rr.rolling_restart(batch_size, fail_count_threshold, None, stale_config_only, None, None, None).wait() except: print "WARNING: Rolling Restart is not available for '%s'. Exiting... " % service.name.lower() print "Executing Restart on service '%s' " % service.name.lower() rr_command = service.restart().wait() return rr_command # Get SMTP server and email sender/receiver info
def send_email_gmail(username, password, email_to, email_from, subject, body, debug=False): # connect to remote mail server and forward message on server = smtplib.SMTP("smtp.gmail.com", 587) message = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s" % (email_from, email_to, subject, body) smtp_sendmail_return = "" if debug: server.set_debuglevel(True) try: server.ehlo() server.starttls() server.login(username,password) smtp_sendmail_return = server.sendmail(email_from, email_to, message) except Exception, e: exception = 'SMTP Exception:\n' + str( e) + '\n' + str( smtp_sendmail_return) finally: server.quit()
def _test_mail(self): try: if self.mail_port == 465: smtp = SMTP_SSL(self.mail_host, port=self.mail_port, timeout=2) else: smtp = SMTP(self.mail_host, port=self.mail_port, timeout=2) smtp.login(self.mail_addr, self.mail_pass) smtp.sendmail(self.mail_addr, (self.mail_addr, ), '''From:%s\r\nTo:%s\r\nSubject:GeekCloud Mail Test!\r\n\r\n Mail test passed!\r\n''' % (self.mail_addr, self.mail_addr)) smtp.quit() return True except Exception, e: color_print(e, 'red') skip = raw_input('????(y/n) [n]? : ') if skip == 'y': return True return False
def _input_smtp(self): while True: self.mail_host = raw_input('???SMTP??: ').strip() mail_port = raw_input('???SMTP?? [25]: ').strip() self.mail_addr = raw_input('?????: ').strip() self.mail_pass = raw_input('?????: ').strip() if mail_port: self.mail_port = int(mail_port) if self._test_mail(): color_print('\n\t?????????, ??????????\n', 'green') smtp = raw_input('????? (y/n) [y]: ') if smtp == 'n': continue else: break print
def connect(threadName, delay, counter, threadID): start = threadID * counter file = open(options.ips,'r') data = file.readlines() while counter: if 0: thread.exit() s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.settimeout(2) try: connect=s.connect((data[start-counter],port)) print "[+] SMTP server on: " + data[start-counter], print "[+] Server added to output file!" logger.write(data[start-counter]) if s.recv(1024): completed.append(data[start-counter].rstrip()) except socket.timeout: print "[-] Server non-existant: " + data[start-counter].rstrip() except socket.error: print "[+] Server exists! " + data[start-counter].rstrip(); print "[-] But it's not SMTP" s.close() time.sleep(delay) counter -= 1
def sendchk(listindex, host, user, password): # seperated function for checking try: smtp = smtplib.SMTP(host) smtp.login(user, password) code = smtp.ehlo()[0] if not (200 <= code <= 299): code = smtp.helo()[0] if not (200 <= code <= 299): raise SMTPHeloError(code, resp) smtp.sendmail(fromaddr, toaddr, message) print "\n\t[!] Email Sent Successfully:",host, user, password print "\t[!] Message Sent Successfully\n" LSstring = host+":"+user+":"+password+"\n" nList.append(LSstring) # special list for AMS file ID's LFile = open(output, "a") LFile.write(LSstring) # save working host/usr/pass to file LFile.close() AMSout = open("AMSlist.txt", "a") AMSout.write("[Server"+str(nList.index(LSstring))+"]\nName="+str(host)+"\nPort=25\nUserID=User\nBccSize=50\nUserName="+str(user)+"\nPassword="+str(password)+"\nAuthType=0\n\n") smtp.quit() except(socket.gaierror, socket.error, socket.herror, smtplib.SMTPException), msg: print "[-] Login Failed:", host, user, password pass
def _connect(self, host, port, retry_interval=60.0): server = None while server is None: self.log.info(u"Connecting to SMTP server {0!r} port {1}".format(host, port)) try: server = yield idiokit.thread( SMTP, host, port, ca_certs=self.smtp_ca_certs, timeout=self.smtp_connection_timeout ) except (socket.error, smtplib.SMTPException) as exc: self.log.error(u"Failed connecting to SMTP server: {0}".format(utils.format_exception(exc))) else: self.log.info(u"Connected to the SMTP server") break self.log.info(u"Retrying SMTP connection in {0:.2f} seconds".format(retry_interval)) yield idiokit.sleep(retry_interval) idiokit.stop(server)
def get_smtp_server(): """ Instanciate, configure and return a SMTP or SMTP_SSL instance from smtplib. :return: A SMTP instance. The quit() method must be call when all the calls to sendmail() have been made. """ uri = parse_uri(config.get('email', 'uri')) if uri.scheme.startswith('smtps'): smtp_server = smtplib.SMTP_SSL(uri.hostname, uri.port) else: smtp_server = smtplib.SMTP(uri.hostname, uri.port) if 'tls' in uri.scheme: smtp_server.starttls() if uri.username and uri.password: smtp_server.login( urllib.unquote_plus(uri.username), urllib.unquote_plus(uri.password)) return smtp_server
def send_email_account(remote_server, remote_port, username, password, email_from, email_to, subject, body): if (remote_server == "smtp.gmail.com"): send_email_gmail(username, password, email_from, email_to, subject, body) else: # connect to remote mail server and forward message on server = smtplib.SMTP(remote_server, remote_port) msg = MIMEMultipart() msg['From'] = email_from msg['To'] = email_to msg['Subject'] = subject msg.attach(MIMEText(body, 'plain')) smtp_sendmail_return = "" try: server.login(username, password) smtp_sendmail_return = server.sendmail(email_from, email_to, msg.as_string()) except Exception, e: print 'SMTP Exception:\n' + str( e) + '\n' + str( smtp_sendmail_return) finally: server.quit()
def send_email_direct(email_from, email_to, subject, body): # find the appropiate mail server domain = email_to.split('@')[1] remote_server = get_mx_record(domain) if (remote_server is None): print "No valid email server could be found for [%s]!" % (email_to) return # connect to remote mail server and forward message on server = smtplib.SMTP(remote_server, 25) msg = MIMEMultipart() msg['From'] = email_from msg['To'] = email_to msg['Subject'] = subject msg.attach(MIMEText(body, 'plain')) smtp_sendmail_return = "" try: smtp_sendmail_return = server.sendmail(email_from, email_to, msg.as_string()) except Exception, e: print 'SMTP Exception:\n' + str( e) + '\n' + str( smtp_sendmail_return) finally: server.quit()
def send_mail(msg, config = None): if not config: config = g_config session = smtplib.SMTP(config['HOST'], config['port']) session.ehlo() session.starttls() session.ehlo() session.login(config['username'], config['pwd']) headers = ["from: " + config['FROM'], "subject: " + config['SUBJECT'], "to: " + config['TO'], "mime-version: 1.0", "content-type: text/html"] headers = "\r\n".join(headers) msg = msg + '\r\n\r\n from ' + hostname + ' \r\n\r\n at ' + cwd session.sendmail(config['FROM'], config['TO'], headers + "\r\n\r\n" + msg)
def parse_args(): parser = argparse.ArgumentParser(description='Send spoofed email message') parser.add_argument('--server', type=str, help='SMTP Server (default localhost)', default="localhost") parser.add_argument('--port', type=int, help='SMTP Port (defaut 25)', default=25) parser.add_argument('--sender', type=str, help='Sender -> from who we send email', required=True) parser.add_argument('--to', type=str, help='Receiver-> to who we send email', required=True) parser.add_argument('--priority', type=int, help='Message priority (default 3)', default=3) parser.add_argument('--reply-to', type=str, help='Reply-To', required=True) parser.add_argument('--subject', type=str, help='Message subject', required=True) return parser.parse_args()
def _connect_smtp(self, force=False): if self.smtp_connection is not None and not force: return True try: logging.debug("Connecting to SMTP server {}:{}".format( self.host, self.port)) smtp = smtplib.SMTP(self.host, self.port) if self.username and self.password: smtp.login(self.username, self.password) self.smtp_connection = smtp except Exception as e: logging.error("Error while connecting to SMTP server: " "{}".format(str(e)), exc_info=True) return False return True
def _send_email(self, from_addr, to_addrs, msg): if self._connect_smtp(): try: try: self.smtp_connection.sendmail(from_addr, to_addrs, msg) return except smtplib.SMTPServerDisconnected as e: logging.debug("SMTP disconnected: {} - reconnecting".format(str(e))) if self._connect_smtp(force=True): self.smtp_connection.sendmail(from_addr, to_addrs, msg) return except Exception as e: logging.error("Error while sending email to {}: " "{}".format(email_addresses, str(e)), exc_info=True)
def flush(self): if len(self.buffer) > 0: try: import smtplib port = self.mailport if not port: port = smtplib.SMTP_PORT smtp = smtplib.SMTP(self.mailhost, port) msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (self.fromaddr, string.join(self.toaddrs, ","), self.subject) for record in self.buffer: s = self.format(record) msg = msg + s + "\r\n" smtp.sendmail(self.fromaddr, self.toaddrs, msg) smtp.quit() except: self.handleError(None) # no particular record self.buffer = []
def _send_mime_text_to_email(self, text, email): """ :type text: mime_text.MIMEText :type email: str :return: """ text['To'] = email try: pass connection = smtplib.SMTP(self._smtp_config['host']) connection.ehlo() connection.starttls() connection.ehlo() connection.login(self._smtp_config['username'], self._smtp_config['password']) connection.sendmail(self._smtp_config['sender'], email, text.as_string()) connection.quit() except smtplib.SMTPException: self._logger.exception('Unable to send email to address "{}"'.format(email))
def _send_mail(self, args): if args is None: raise RuntimeError("Passed argument for send mail is not set!") if len(args) != 2: raise RuntimeError("Passed argument for send mail has invalid number of arguments!") subject = args[0] text = args[1] msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = self.mail_sender msg['To'] = ', '.join(self.mail_receiver_list) msg.attach(MIMEText(text)) msg_string = msg.as_string() logging.debug(msg_string) smtp_conn = smtplib.SMTP(self.mail_server) smtp_conn.sendmail(self.mail_sender, self.mail_receiver_list, msg_string) smtp_conn.quit()
def send_message(self, email_content): # ??????? now = datetime.datetime.now() header = self.smtp_email_header + '[' + str(now.month) + '-' + str(now.day) + ' ' + \ str(now.hour) + ':' + str(now.minute) + ':' + str(now.second) + ']' msg = MIMEText(email_content, 'plain', 'utf-8') msg['from'] = self.smtp_from_addr msg['to'] = self.smtp_to_addr msg['Subject'] = Header(header, 'utf-8').encode() # ?? try: smtp_server = smtplib.SMTP(self.smtp_server_host, self.smtp_server_port) smtp_server.login(self.smtp_from_addr, self.smtp_server_password) smtp_server.sendmail(self.smtp_from_addr, [self.smtp_to_addr], msg.as_string()) smtp_server.quit() except Exception as e: if log.isEnabledFor(logging.ERROR): log.error("??????") log.exception(e)
def send(self, target: str, subject: str, html_content_with_cids: str, inline_png_cids_filenames: {str : str}): msg = EmailMessage() msg['Subject'] = subject msg['From'] = self.sender msg['To'] = target msg.set_content('') msg.add_alternative( html_content_with_cids, subtype='html' ) for png_cid in inline_png_cids_filenames: full_path_to_png = os.path.abspath(os.path.join( os.path.dirname(__file__), inline_png_cids_filenames[png_cid] )) with open(full_path_to_png, 'rb') as png_file: file_contents = png_file.read() msg.get_payload()[1].add_related(file_contents, 'image', 'png', cid=png_cid) with smtplib.SMTP(self.smtp_server_host, self.smtp_server_port) as smtp_connection: smtp_connection.starttls() smtp_connection.login(self.username, self.password) smtp_connection.send_message(msg)
def send_email(self): self.make_messages() if len(self.email_messages) > 0: for detail in self.email_messages: user_email = detail['email'] user_message = detail['message'] try: email_conn = smtplib.SMTP(host, port) email_conn.ehlo() email_conn.starttls() email_conn.login(username, password) the_msg = MIMEMultipart("alternative") the_msg['Subject'] = "Billing Update!" the_msg["From"] = from_email the_msg["To"] = user_email part_1 = MIMEText(user_message, 'plain') the_msg.attach(part_1) email_conn.sendmail(from_email, [user_email], the_msg.as_string()) email_conn.quit() except smtplib.SMTPException: print("error sending message") return True return False
def send_email(sender, sender_pass, receiver, subject, body): # Create email msg = MIMEText(body) msg['Subject'] = subject msg['From'] = sender msg['To'] = receiver # Send email out server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(sender, sender_pass) server.send_message(msg) server.quit() # Gets and caches your gmail address
def send_mail(to_list,sub,context): me = mail_user msg = MIMEText(context) msg['Subject'] = sub msg['From'] = me msg['To'] = ";".join(to_list) try: s = smtplib.SMTP(mail_host) s.login(mail_user,mail_pass) s.sendmail(me, to_list, msg.as_string()) s.quit() return True except Exception, e: return False
def send_exception_mail(exception): # noinspection PyBroadException try: msg = MIMEMultipart('alternative') msg['Subject'] = "Exception Occurred on betaPika" msg['From'] = FROM_MAIL msg['To'] = TO_MAIL plain = MIMEText(exception, "plain", "utf-8") msg.attach(plain) s = smtplib.SMTP() s.connect(SERVER, PORT) s.ehlo() s.starttls() s.ehlo() s.login(FROM_MAIL, FROM_PASSWORD) s.sendmail(FROM_MAIL, TO_MAIL, msg.as_string()) s.quit() except: print "Mail Failed"
def sender(username, password, toaddress, email_text): fromaddr = username toaddrs = toaddress now = datetime.datetime.now() msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddrs msg['Subject'] = "Tv shows [ " + now.strftime('%Y/%m/%d') + " ]" msg.attach(MIMEText(email_text, 'plain')) text = msg.as_string() # Credentials (if needed) username = username password = password # The actual mail send server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login(username, password) server.sendmail(fromaddr, toaddrs, text) server.quit()