def flush(self): from smtplib import SMTP import settings, logging if not self.messages: return msg = 'To: ' + settings.to_addr + '\n' msg += 'From: ' + settings.from_addr + '\n' if len(self.messages) == 1: msg += 'Subject: mmonitor: ' + self.messages[0][:200] + '\n' else: msg += 'Subject: mmonitor: multiple notices\n' msg += '\n\n' msg += '\n'.join(self.messages) msg += '\n\n' logging.info('sending mail:\n%s', '\n'.join(self.messages)) smtp = SMTP(settings.smtp_host, settings.smtp_port) if settings.smtp_tls: smtp.starttls() smtp.ehlo_or_helo_if_needed() if settings.smtp_user: smtp.login(settings.smtp_user, settings.smtp_password) smtp.sendmail(settings.from_addr, settings.to_addr, msg) smtp.close() self.messages = []
def send_email(content, destination, subject, file): try: msg = MIMEMultipart() msg['Subject']= subject msg['From'] = sender # some SMTP servers will do this automatically, not all fp = open(file, 'rb') # Open File name "file" img = MIMEImage(fp.read()) # Read the file. fp.close() # Good housekeeping: close the file. msg.attach(img) # Attach the file to the message. conn = SMTP(SMTPserver, port = 587, timeout = 60) # timeout is critical here for long term health. conn.ehlo() conn.starttls() conn.ehlo() conn.login(USERNAME, PASSWORD) conn.set_debuglevel(1) try: conn.sendmail(sender, destination, msg.as_string()) finally: conn.close() except Exception as exc: # Print a message error! print("Mail failed; %s" % str(exc)) print("Moving on!")
def mail_sender(self): send_fails = [] for person in self.to: message = MIMEMultipart() person = person.strip(" ") message["To"] = "{}".format(person) message["From"] = "{}".format(self.user_id) message["Subject"] = self.subject content_text = self.text + "\n\nThis mail was sent via E-Mapp.\nE-Mapp Source Code: https://github.com/MERTULAS/E-Mapp\n" content = MIMEText(content_text, "plain") message.attach(content) for file in self.files: pdf = MIMEApplication(open(file, 'rb').read()) pdf.add_header('Content-Disposition', 'attachment', filename=file.split("/")[-1]) message.attach(pdf) try: mail = SMTP("smtp.gmail.com", 587) mail.ehlo() mail.starttls() mail.login(self.user_id, self.user_pass) mail.sendmail(message["From"], message["To"], message.as_string()) mail.close() except: send_fails.append("-" + person) return send_fails
def send_mail(send_to, subject, text, files=[], server='localhost', username=None, password=None): send_from = '*****@*****.**' msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(text)) for f in files: part = MIMEBase('application', 'octet-stream') part.set_payload(open(f, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % basename(f)) msg.attach(part) smtp = SMTP(server) if username is not None: smtp.login(str(username), str(password)) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def send_mail(send_from, send_to, subject, text, files=[], server='smtp.typa.ru'): from smtplib import SMTP from os import path from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders from email.header import Header assert type(send_to)==list assert type(files)==list msg = MIMEMultipart() msg['From'] = Header(send_from.decode("utf-8")).encode() msg['To'] = Header(COMMASPACE.join(send_to).decode("utf-8")).encode() msg['Date'] = formatdate(localtime=True) msg['Subject'] = Header(subject.decode("utf-8")).encode() msg.attach( MIMEText(text,'plain','UTF-8') ) for f in files: part = MIMEBase('application', "octet-stream") part.set_payload( open(f,"rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % path.basename(f)) msg.attach(part) smtp = SMTP(server, 25) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def run(self): # Serialize/flatten the message fp = StringIO() g = Generator(fp, mangle_from_=False) g.flatten(self.msg) contents = fp.getvalue() for rcpt in self.rcpts: rcpt = utils.find_address(rcpt) smtp_server = self.MXLookup(rcpt) conn = SMTP(smtp_server, timeout=30) conn.set_debuglevel(True) try: conn.ehlo() # FIXME: we should support an option to refuse to send messages # if the server doesn't support STARTTLS. if conn.has_extn('starttls'): conn.starttls() conn.ehlo() # TODO: should catch exceptions here and either retry later or # send a delivery report back to the author. conn.sendmail(self.from_, rcpt, contents) finally: conn.close()
def sendmail(self, destination, subject, message, attach=None): try: msg = MIMEMultipart() msg['From'] = self.username msg['Reply-to'] = self.username msg['To'] = destination msg['Subject'] = subject msg.attach(MIMEText(message)) if attach: part = MIMEBase('application', 'octet-stream') part.set_payload(open(attach, 'rb').read()) Encoders.encode_base64(part) part.add_header( 'Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attach)) msg.attach(part) mailServer = SMTP("smtp.gmail.com", 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() try: mailServer.login(self.username, self.password) mailServer.sendmail(self.username, destination, msg.as_string()) finally: mailServer.close() except Exception, exc: sys.exit("Failed to send mail; %s" % str(exc))
class Email: def __init__( self, name, psw ): self.name = name self.psw = psw self.to = raw_input('To : ') self.subject = 'Subject : %s\n' % raw_input('Subject : ') self.msg = raw_input('Msg : ') self.failed = {} def __str__( self ): return 'From : ' + self.name + '\nTo : ' + \ str(self.to) + '\n' + self.subject + '\nBody : ' + self.msg def __start_server( self ): if SSL: self.server = SMTP_SSL( SERVER, PORT ) else: self.server = SMTP( SERVER, PORT ) self.server.ehlo() self.server.starttls() self.server.ehlo() def send( self ): self.__start_server() try: self.server.login( self.name, self.psw ) except SMTPAuthenticationError: print('Wrong user or psw') sys.exit(0) else: self.failed = self.server.sendmail( self.name, self.to, self.subject + self.msg ) self.server.close()
def sendFildByMail(config): message = MIMEMultipart() message['from'] = config['from'] message['to'] = config['to'] message['Reply-To'] = config['from'] message['Subject'] = config['subject'] message['Date'] = time.ctime(time.time()) message['X-Priority'] = '3' message['X-MSMail-Priority'] = 'Normal' message['X-Mailer'] = 'wendell client' message['X-MimeOLE'] = 'product by wendell client v1.0.00' # 注意这一段 f = open(config['file'], 'rb') file = MIMEApplication(f.read()) f.close() file.add_header('Content-Disposition', 'attachment', filename = os.path.basename(config['file'])) message.attach(file) smtp = SMTP(config['server'], config['port']) smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login(config['username'], config['password']) print 'OK' print 'Send ...' smtp.sendmail(config['from'], [config['from'], config['to']], message.as_string()) print 'OK' smtp.close()
def main(smtp_data, email_data, address): """ Main function """ month = datetime.now().month # Loading the current month text = """<p>Olá,<br> Vocês poderiam me enviar o boleto do aluguel do mês atual, com vencimento no próximo dia 10? Meu imóvel é o da <b>{address}</b></p> <p>Obrigado!</p> """ subject = "Boleto de aluguel do mês {month}" message = MIMEText(text.format(address=address), 'html') message['Subject'] = subject.format(month=month) message['From'] = email_data['sender'] message['To'] = email_data['receiver'] message['Reply-To'] = email_data['reply_to'] server = SMTP(host=smtp_data['server'], port=smtp_data['port']) server.ehlo() server.starttls() server.login(smtp_data['username'], smtp_data['password']) server.send_message(message) server.close()
def _emailer(self, subject, text): #Function to email list on startup of ganga (following restart by cronjob) from email.MIMEText import MIMEText from smtplib import SMTP emailcfg = Ganga.Utility.Config.getConfig('Robot') host = emailcfg['FileEmailer_Host'] from_ = emailcfg['FileEmailer_From'] recipients = [recepient.strip() for recepient in \ emailcfg['FileEmailer_Recipients'].split(',') \ if recepient.strip()] subject = "Ganga - TestRobot automatic restart by crontab" if not recipients: logger.warn('No recpients specified - email will not be sent') return logger.info("emailing files to %s." %(recipients)) text = "GangaTestRobot restarted on: %s" %(datetime.datetime.now().strftime("%H:%M:%S %d %b %Y")) msg = MIMEText(text) msg['Subject'] = subject msg['From'] = from_ msg['To'] = ', '.join(recipients) #send message session = SMTP() try: session.connect(host) session.sendmail(from_, recipients, msg.as_string()) session.quit() except: logger.error("Failed to send notification of start-up") session.close()
def send_mail(self): """Used to send the email.""" # Set up the message basics msg = MIMEMultipart() msg['From'] = self.from_email msg['To'] = ', '.join(self.mailing_list) msg['Subject'] = self.subject print msg # Set the message body msg.attach(MIMEText(self.body)) # Process attachments for filename in self.attachments: with open(filename, "rb") as f: msg.attach(MIMEApplication( f.read(), Content_Disposition='attachment; filename="%s"' % basename(filename), Name=basename(filename) )) # Configure and send the mail s = SMTP('localhost') s.sendmail(self.from_email, self.mailing_list, msg.as_string()) s.close()
def send_mail(email, senha, receber, mensagem, vezes): try: from smtplib import SMTP import time x = 1 gmail = SMTP('smtp.gmail.com:587') gmail.ehlo() gmail.starttls() gmail.login(email, senha) while x <= vezes: gmail.sendmail(email, receber, mensagem) print("[%d]Enviado!" % x) x += 1 gmail.close() time.sleep(2) except KeyboardInterrupt: print("\n\n[!] Interrompendo o envio de emails!") time.sleep(3) except ImportError: print("[!] Erro de importação, biblioteca: smtplib,time") except: print("\n[!] Erro de Autenticação! (Logins externos não estão permitidos no seu gmail ou Login incorreto ou Rementente não encontrado") print("\nEspere 10 segundos") time.sleep(10)
def execute(self, runid): """Send files as an email. Keyword arguments: runid -- A UTC ID string which identifies the run. The following parameters are loaded from the Robot configuration: FileEmailer_Host e.g. localhost or localhost:25 FileEmailer_Type e.g. text or html FileEmailer_From e.g. [email protected] FileEmailer_Recipients e.g. [email protected], [email protected] FileEmailer_Subject e.g. Report ${runid}. FileEmailer_TextFile e.g. ~/gangadir/robot/report/${runid}.txt FileEmailer_HtmlFile e.g. ~/gangadir/robot/report/${runid}.html If Recipients are not specified then no email is sent. In Subject, TextFile and HtmlFile the token ${runid} is replaced by the runid argument. If Type is text, then TextFile is sent. If Type is html, then HtmlFile is sent, or if TextFile is also specified then a multipart message is sent containing TextFile and HtmlFile. """ # get configuration properties host = self.getoption('FileEmailer_Host') type = self.getoption('FileEmailer_Type') from_ = self.getoption('FileEmailer_From') # extract recipients ignoring blank entries recipients = [recipient.strip() for recipient in \ self.getoption('FileEmailer_Recipients').split(',') \ if recipient.strip()] subject = Utility.expand(self.getoption('FileEmailer_Subject'), runid = runid) textfilename = Utility.expand(self.getoption('FileEmailer_TextFile'), runid = runid) htmlfilename = Utility.expand(self.getoption('FileEmailer_HtmlFile'), runid = runid) if not recipients: logger.warn('No recipients specified. Email will not be sent.') return logger.info('Emailing files to %s.', recipients) # build message if type == 'html': msg = self._gethtmlmsg(textfilename, htmlfilename) else: msg = self._gettextmsg(textfilename) msg['Subject'] = subject msg['From'] = from_ msg['To'] = ', '.join(recipients) # send message session = SMTP() try: session.connect(host) session.sendmail(from_, recipients, msg.as_string()) session.quit() finally: session.close() logger.info('Files emailed.')
def email_facture(): msg = MIMEMultipart() enc = 'latin-1' msg['Subject'] = request.form['subject'].encode(enc) msg['From'] = u'Société Roucet <*****@*****.**>'.encode(enc) to_list = re.split('[ ,;:\t\n]+', request.form['email_addresses']) msg['To'] = COMMASPACE.join(to_list) msg['Reply-to'] = '*****@*****.**' try: msg.attach(MIMEText(request.form['msg'].encode(enc), 'plain', enc)) except: msg.attach(MIMEText(request.form['msg'].encode('utf8'), 'plain', 'utf8')) if 'include_pdf' in request.form: out_fn = _generate_facture(g, request.form['no_commande_facture']) part = MIMEApplication(open(out_fn, "rb").read()) part.add_header('Content-Disposition', 'attachment', filename="facture_roucet.pdf") msg.attach(part) mailer = SMTP('mail.roucet.com', 587) mailer.login('*****@*****.**', SMTP_PW) mailer.sendmail(msg['From'], to_list, msg.as_string()) mailer.close() # if user is admin, set facture_est_envoyee to True, if repr, this will # be done in the next ajax call (to /representant/set_facture_est_envoyee) if not current_user.u['representant_id']: pg.update(g.db.cursor(), 'commande', set={'facture_est_envoyee': True}, where={'no_commande_facture': request.form['no_commande_facture']}) g.db.commit() return {'success': True}
def send(email_subject, email_content): if 'DRC_SMTP_SERVER' not in os.environ: logger.error("email variables not set!") return 1 smtp_server = os.environ['DRC_SMTP_SERVER'] sender = os.environ['DRC_SENDER'] destination = [os.environ['DRC_DESTINATION']] username = os.environ['DRC_USERNAME'] password = os.environ['DRC_PASSWORD'] try: text_subtype = 'html' msg = MIMEText(email_content, text_subtype) msg['Subject'] = email_subject msg['From'] = sender conn = SMTP(smtp_server) conn.set_debuglevel(False) conn.login(username, password) try: logger.info('sending mail....') conn.sendmail(sender, destination, msg.as_string()) finally: conn.close() return 0 except Exception, exc: logger.info('sending failed: %s' % str(exc)) return 1
def send_mail(email, senha, receber, mensagem, vezes): try: from smtplib import SMTP import time x = 1 gmail = SMTP('smtp.gmail.com:587') gmail.ehlo() gmail.starttls() gmail.login(email, senha) while x <= vezes: gmail.sendmail(email, receber, mensagem) print("[%d]Enviado!" % x) x += 1 gmail.close() time.sleep(2) except KeyboardInterrupt: print("\n\n[!] Interrompendo o envio de emails!") time.sleep(3) except ImportError: print("[!] Erro de importação, biblioteca: smtplib,time") except: print( "\n[!] Erro de Autenticação! (Logins externos não estão permitidos no seu gmail ou Login incorreto ou Rementente não encontrado" ) print("\nEspere 10 segundos") time.sleep(10)
def sendMail(sub,body,recipients): global ldap # IITB SMTP server SMTPserver = "smtp-auth.iitb.ac.in" # sender of the mail (Details removed) sender = formataddr(("Placements","I AM THE SENDER (email id offcourse)")) msg = MIMEMultipart('alternative') msg['Subject'] = "[PB]: "+sub msg['From'] = sender msg['To'] = ",".join(recipients) # Record the MIME types of both parts - text/plain and text/html. part2 = MIMEText(body, '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(part2) # Send the message via local SMTP server. try: conn = SMTP(SMTPserver) conn.set_debuglevel(False) conn.starttls() conn.login(ldap[0],ldap[1]) try: conn.sendmail(sender,recipients,msg.as_string()) finally: conn.close() except Exception, exc: logger.error("Mail Send Failed: " + str(exc))
class EmailConnection(object): def __init__(self): self.connect() def connect(self): self.connection = SMTP('smtp.gmail.com', 587) self.connection.ehlo() self.connection.starttls() self.connection.ehlo() self.connection.login('*****@*****.**', '*********') def send(self, message, from_=None, to=None): if type(message) == str: if from_ is None or to is None: raise ValueError('You need to specify `from_` and `to`') else: from_ = get_email(from_) to = get_email(to) else: from_ = message.email['From'] if 'Cc' not in message.email: message.email['Cc'] = '' to_emails = [message.email['To']] + message.email['Cc'].split(',') to = [get_email(complete_email) for complete_email in to_emails] message = str(message) return self.connection.sendmail(from_, to, message) def close(self): self.connection.close()
def auto_sendEmail(to_list, theme, new_file): mail_host = "smtp.caixin.com" # 使用的邮箱的smtp服务器地址,这里是163的smtp地址 mail_user = "******" # 用户名 mail_pass = "******" # 密码 mail_postfix = "caixin.com" # 邮箱的后缀,网易就是163.com me = "<" + mail_user + "@" + mail_postfix + ">" msg = MIMEMultipart() msg['Subject'] = theme msg['From'] = me msg['To'] = ",".join(to_list) # 将收件人列表以','分隔 # 正文 content = "<html><head><title>我的第一个 HTML 页面</title></head><body><p>body 元素的内容会显示在浏览器中。</p>" \ "<p>title 元素的内容会显示在浏览器的标题栏中。</p></body></html>" signature = "<br><br><br><span id='spnEditorSign'><br>--<br>********<br>********<br>********<br>" \ "<br>Mail: ********<br>Tel: (+86)********<br>WeChat: ********<br>" \ "Addr: ********</span>" contentpart = MIMEText(content + signature, 'html', 'utf-8') msg.attach(contentpart) # 附件 attachpart = MIMEApplication(open(new_file, 'r', encoding='utf-8').read()) attachpart.add_header('Content-Disposition', 'attachment', filename=new_file) msg.attach(attachpart) try: server = SMTP() server.connect(mail_host) # 连接服务器 server.login(mail_user, mail_pass) # 登录操作 server.sendmail(me, to_list, msg.as_string()) server.close() return True except Exception as e: print(str(e)) return False
def send_email(content, destination, subject, file): try: msg = MIMEMultipart() msg['Subject']= subject msg['From'] = sender # some SMTP servers will do this automatically, not all fp = open(file, 'rb') # Open File name "file" img = MIMEImage(fp.read()) # Read the file. fp.close() # Good housekeeping: close the file. msg.attach(img) # Attach the file to the message. conn = SMTP(SMTPserver, port = 587, timeout = 60) # timeout is critical here for long term health. conn.ehlo() conn.starttls() conn.ehlo() conn.login(USERNAME, PASSWORD) conn.set_debuglevel(1) try: conn.sendmail(sender, destination, msg.as_string()) finally: conn.close() except Exception as exc: # Print a message error! print(("Mail failed; %s" % str(exc))) print("Moving on!")
def sendmail(subject: str, content: str, receiver: List[str], sender: str = '*****@*****.**', files=List[str], password: str = '-1Yxc/+]'): msg = MIMEMultipart() msg['From'] = sender msg['To'] = COMMASPACE.join(receiver) msg['Subject'] = subject msg.attach(MIMEText(content, _subtype='html')) for f in files or []: with open(f, "rb") as fil: part = MIMEApplication(fil.read(), Name='Dokumente.zip') # After the file is closed part['Content-Disposition'] = 'attachment; filename="Dokumente.zip"' msg.attach(part) conn = SMTP('mail.netzone.ch') conn.set_debuglevel(False) conn.login(sender, password) conn.sendmail(sender, receiver, msg.as_string()) conn.close()
def enviarCorreo(request): template = loader.get_template('personal/contact.html') nombre = request.POST.get('nombre') apellido = request.POST.get('apellido') email = request.POST.get('email') telefono = request.POST.get('telefono') mensaje = request.POST.get('mensaje') passwordE = request.POST.get('password') mensajeE = '' mensajeE += 'Nombre: ' + nombre + '\n' mensajeE += 'Apellido: ' + apellido + '\n' mensajeE += 'Telefono: ' + telefono + '\n' mensajeE += mensaje + '\n' destino = "*****@*****.**" asunto = "necesito contactar" EnviarCorreo = SMTP() EnviarCorreo.connect("smtp.gmail.com", 587) EnviarCorreo.starttls() EnviarCorreo.ehlo() EnviarCorreo.login(email, passwordE) Cabecera = 'To:' + destino + '\n' Cabecera += 'From: ' + email + '\n' Cabecera += 'Subject: ' + asunto + '\n' + '\n' EnviarCorreo.sendmail(email, destino, Cabecera + mensajeE) EnviarCorreo.close() return HttpResponseRedirect(reverse('personal:contact'))
def send_mail(obj, message): try: json = read_json_file(message) dict_email_params = read_json_file( join(realpath(''), "configuration", "email_config.json")) smtp_server = dict_email_params["smtp_server"] port = dict_email_params["port"] user = dict_email_params["user"] password = dict_email_params["password"] subject = dict_email_params["subject"] send_to = dict_email_params["send_to"] msg = MIMEMultipart() msg['From'] = subject msg['To'] = send_to msg['Subject'] = obj msg.attach(MIMEText(str(json))) server = SMTP(smtp_server, port) server.ehlo() server.starttls() server.login(user, password) server.send_mail(subject, send_to, msg.as_string()) server.close() return True except: return False
def send_email( self, subject, content, recipients="", sender=None, filename=None, file_content=None, ): sender = sender or self.settings["mail"]["sender"] message = MIMEMultipart() message["From"] = sender message["To"] = recipients message["Date"] = formatdate(localtime=True) message["Subject"] = subject message.attach(MIMEText(content)) if filename: attached_file = MIMEApplication(file_content, Name=filename) attached_file[ "Content-Disposition"] = f'attachment; filename="{filename}"' message.attach(attached_file) server = SMTP(self.settings["mail"]["server"], self.settings["mail"]["port"]) if self.settings["mail"]["use_tls"]: server.starttls() password = environ.get("MAIL_PASSWORD", "") server.login(self.settings["mail"]["username"], password) server.sendmail(sender, recipients.split(","), message.as_string()) server.close()
def send_email(self, subject, message, recipient=None): """Send an email. Args: subject (str): email subject message (str): email message recipient (list): email recipients Returns: (bool): True if successful, False if otherwise """ target_recipient = self.recipient if recipient is None else recipient for i in target_recipient: for _ in range(self.max_retries): try: server = SMTP(self.server, self.port) server.starttls() server.login(self.sender, self.sender_pass) server.sendmail(self.sender, i, ( f"From: {self.sender}\n" f"To: {i}\n" f"Subject: {subject.encode('ascii', errors='ignore').decode()}\n\n" f"{message.encode('ascii', errors='ignore').decode()}" )) break except Exception as e: logger.write(DEBUG, f"Emailer.send_email - {repr(e)}") finally: server.close() else: return False return True
def mailalert(sender,destination,smtpServer,subject,content,debugLevel): # Only needed for S/SMTP #USERNAME = "******" #PASSWORD = "******" # typical values for text_subtype are plain, html, xml text_subtype = 'plain' try: msg = MIMEText(content, text_subtype) msg['Subject']= subject #print "Connect to SMTP server..." conn = SMTP(smtpServer) conn.set_debuglevel(debugLevel) #conn.login(USERNAME, PASSWORD) try: #print "Sending e-mail..." conn.sendmail(sender, destination, msg.as_string()) finally: #print "Closing SMTP connection..." conn.close() return True except Exception, exc: #print "Failed to send email" #sys.exit( "mail failed; %s" % str(exc) ) return False
def send_mail(subject, content, cfg): # typical values for text_subtype are plain, html, xml text_subtype = 'plain' msg = MIMEText(content, text_subtype) msg['Subject'] = subject msg['From'] = cfg.get( 'Mail', 'sender') # some SMTP servers will do this automatically, not all if not cfg.get('Mail', 'SMTPServer'): mainlog.error("Mail configuration seems broken. Can't send email.") # Since this is backup, failing sending a mail should not stop # the execution => no exception thrown return conn = SMTP(cfg.get('Mail', 'SMTPServer')) conn.set_debuglevel(False) # conn.login(cfg.get('Mail','SMTPUser'), cfg.get('Mail','SMTPPassword')) try: conn.sendmail(cfg.get('Mail', 'sender'), cfg.get('Mail', 'destination'), msg.as_string()) except Exception as ex: mainlog.error("Unable to send mail") finally: conn.close() mainlog.info("Mail sent")
def run(self): u"""Surchage de la méthode QThread.run() Envoit l'email et notifie les erreurs """ try: # Pour gmail, connexion smtp_ssl avec port par défaut # et pas de starttls server = SMTP(self.__conf["serveur"], 587, "localhost", DEFAULT_TIMEOUT) server.starttls() server.login(self.__email['From'], self.__password) server.sendmail(self.__email['From'], self.__email['To'], self.__email.as_string()) server.close() self.sentSignal.emit(MailSender.MAIL_ERROR_NONE) except SMTPAuthenticationError: self.sentSignal.emit(MailSender.MAIL_ERROR_AUTHENTICATION) except gaierror: self.sentSignal.emit(MailSender.MAIL_ERROR_CONNECTION) except SMTPServerDisconnected: self.sentSignal.emit(MailSender.MAIL_ERROR_TIMEOUT) except Exception, e: print e self.sentSignal.emit(MailSender.MAIL_ERROR_OTHER)
def send_email( self, subject, content, sender=None, recipients=None, filename=None, file_content=None, ): sender = sender or self.mail_sender recipients = recipients or self.mail_recipients message = MIMEMultipart() message["From"] = sender message["To"] = recipients message["Date"] = formatdate(localtime=True) message["Subject"] = subject message.attach(MIMEText(content)) if filename: attached_file = MIMEApplication(file_content, Name=filename) attached_file[ "Content-Disposition"] = f'attachment; filename="{filename}"' message.attach(attached_file) server = SMTP(self.mail_server, self.mail_port) if self.mail_use_tls: server.starttls() server.login(self.mail_username, self.mail_password) server.sendmail(sender, recipients.split(","), message.as_string()) server.close()
def notify(self, way="email", **msg): self.t1 = time.time() data = self.Id+" ends on "+str(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(self.t1)))+ \ " after running for "+str(self.t1 - self.t0)+" seconds" data = msg.get("data", data) self.log.info(data) if way == "print": return from smtplib import SMTP TO = msg.get("to", ["*****@*****.**"]) FROM = "*****@*****.**" SMTP_HOST = "smtp.163.com" user= "******" passwords="jiangxiaoke" mailb = ["paper ends", data] mailh = ["From: "+FROM, "To: [email protected]", "Subject: Paper ends "+str(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(self.t1)))+\ "TotalN=" + str(Case.TotalN) +" SuccessN="+str(Case.SuccessN)+ " ExistingN="+str(Case.ExistingN) +" FailN="+str(Case.FailN)] mailmsg = "\r\n\r\n".join(["\r\n".join(mailh), "\r\n".join(mailb)]) send = SMTP(SMTP_HOST) send.login(user, passwords) rst = send.sendmail(FROM, TO, mailmsg) if rst != {}: self.log.warn("send mail error: "+str(rst)) else: self.log.info("sending mail finished") send.close()
def send_email(text, receivers, subject, sender=SENDER, smtp_server=SMTP_SERVER): """ Send an email from SENDER_EMAIL to all provided receivers :param text: string, body of email :param receivers: list, email receivers :param subject: string, email subject :param sender: string, sender email :param smtp_server: string, smtp server hostname """ logger.info('Sending email to: %s', str(receivers)) msg = MIMEMultipart() msg['From'] = sender msg['To'] = COMMASPACE.join(receivers) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(text)) smtp = SMTP(smtp_server) smtp.sendmail(sender, receivers, msg.as_string()) smtp.close() logger.debug('Email sent')
def email(results, host, user, password, recipients, addendum=None): # Build message. winners = [ '<li style="font-weight: bold; font-style: italic;">{}</li>' .format(o.name) if o.premium else '<li>{}</li>'.format(o.name) for o in results ] message = ( '<p>Voting complete! Here are the results:</p><ul>{}</ul></p>' .format('\n'.join(winners)) ) if addendum: message += '<p>{}</p>'.format(addendum) message = MIMEText(message, 'html') message['subject'] = 'Vote: Results' message['to'] = ', '.join(recipients) # Set up SMTP. smtp = SMTP(host) smtp.starttls() smtp.login(user, password) # Send message. smtp.sendmail(user, recipients, message.as_string()) smtp.close()
def sendMail(rcpt, subject, body, files=[]): send_from = "*****@*****.**" msg = MIMEMultipart() msg['From'] = send_from if rcpt is None: rcpt = admin_email msg['To'] = COMMASPACE.join(rcpt) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(body) ) for f,b in files: logger.debug("SEND ATT "+f) part = MIMEBase('application', "octet-stream") part.set_payload(open(f).read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(b)) msg.attach(part) server = SMTP(smtphost, smtpport) server.sendmail(send_from, rcpt, msg.as_string()) server.close()
def sendmail(subject, text): msg = create_message(from_name, to_address, subject, text, mail_charset) s = SMTP('smtp.gmail.com', 587) s.ehlo(), s.starttls(), s.ehlo() s.login(from_address, from_password) s.sendmail(from_address, to_address, msg.as_string()) s.close()
def run(self): sub_header = clientid if self.jobid: sub_header = 'Client:{} {}'.format(clientid, self.jobid) elif self.checkin: sub_header = 'This:{}'.format(clientid) print "this is <{}>".format(sub_header) msg = MIMEMultipart() msg['From'] = sub_header msg['To'] = EMAIL_USERNAME msg['Subject'] = sub_header msgtext = json.dumps({ 'os': sys_obj.systemver, 'user': sys_obj.User, 'arc': sys_obj.architecture, 'PCname': sys_obj.PCname, 'msg': self.text }) #print msgtext msg_str = being_secure.encrypt(msgtext) #print msg_str msg.attach(MIMEText(msg_str)) smtpServer = SMTP() smtpServer.connect(EMAIL_SERVER, SERVER_PORT) smtpServer.starttls() smtpServer.login(EMAIL_USERNAME, EMAIL_PASSWORD) smtpServer.sendmail(EMAIL_USERNAME, EMAIL_USERNAME, msg.as_string()) smtpServer.close()
def main(): """ entry point """ server = SMTP(SMTP_HOST) # server.ehlo() # print(server.ehlo()) server.starttls() print(server.ehlo(LOCAL_HOST)) user = raw_input('user: '******'password: '******'*****@*****.**' toaddrs = '*****@*****.**' msg = "\r\n".join([ "From: [email protected]", "To: [email protected]", "Subject: Buildbot", "", "Why, oh why" ]) server.sendmail(fromaddr, toaddrs, msg) server.close()
def create_and_send_mail_messages(messages): if not settings.EMAIL_HOST: return sender = Header(unicode(settings.APP_SHORT_NAME), 'utf-8') sender.append('<%s>' % unicode(settings.DEFAULT_FROM_EMAIL)) sender = u'%s <%s>' % (unicode(settings.APP_SHORT_NAME), unicode(settings.DEFAULT_FROM_EMAIL)) try: connection = SMTP(str(settings.EMAIL_HOST), str(settings.EMAIL_PORT)) """ connection = SMTP(str(settings.EMAIL_HOST), str(settings.EMAIL_PORT), local_hostname=DNS_NAME.get_fqdn()) """ if (bool(settings.EMAIL_USE_TLS)): connection.ehlo() connection.starttls() connection.ehlo() if settings.EMAIL_HOST_USER and settings.EMAIL_HOST_PASSWORD: connection.login(str(settings.EMAIL_HOST_USER), str(settings.EMAIL_HOST_PASSWORD)) if sender is None: sender = str(settings.DEFAULT_FROM_EMAIL) for recipient, subject, html, text, media in messages: msgRoot = MIMEMultipart('related') msgRoot['Subject'] = Header(subject, 'utf-8') msgRoot['From'] = sender to = Header(recipient.username, 'utf-8') to.append('<%s>' % recipient.email) msgRoot['To'] = to #msgRoot.preamble = 'This is a multi-part message from %s.' % unicode(settings.APP_SHORT_NAME).encode('utf8') msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgAlternative.attach(MIMEText(text.encode('utf-8'), _charset='utf-8')) msgAlternative.attach(MIMEText(html.encode('utf-8'), 'html', _charset='utf-8')) for alias, location in media.items(): fp = open(location, 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<'+alias+'>') msgRoot.attach(msgImage) try: connection.sendmail(sender, [recipient.email], msgRoot.as_string()) except Exception, e: logging.error("Couldn't send mail using the sendmail method: %s" % e) try: connection.quit() except socket.sslerror: connection.close()
def sendEmail(toAddr, subject, content, attachments=None): # init email addresses fromAddr = "*****@*****.**" # init connection server = SMTP('smtp.office365.com', 587) server.ehlo() server.starttls() server.ehlo() passwd = b'WXo1NDIwMDk4' server.login(fromAddr, b64decode(passwd).decode('utf-8')) # init message msg = MIMEMultipart() msg['From'] = fromAddr msg['Subject'] = subject msg.attach(MIMEText(content, 'plain')) if attachments: for att in attachments: if path.exists(att): if path.isdir(att): for filename in listdir(att): attachFiletoEmail(msg, '{}/{}'.format(att, filename)) else: attachFiletoEmail(msg, att) # send message for dst in toAddr: msg['To'] = dst text = msg.as_string() try: server.sendmail(fromAddr, dst, text) except Exception as e: print('Sending email failed, error:[{}]'.format(e)) server.close()
class EmailConnection(object): def __init__(self, username, password): self.username = username self.password = password self.connect_to_gmail() def connect_to_gmail(self): self.connection = SMTP('smtp.gmail.com', 587) self.connection.starttls() self.connection.ehlo() self.connection.login(self.username, self.password) def send(self, message, to=None, subject=None): if isinstance(message, basestring): if to is None or subject is None: raise ValueError('You need to specify both `to` and `subject`') else: message = Email( from_=self.username, to=to, subject=subject, message=message ) from_ = message.email['From'] to = message.email['To'].split(',') if 'Cc' in message.email: to = to + message.email['Cc'].split(',') message = str(message) self.connection.sendmail(from_, to, message) self.connection.close()
def send_email( self, subject: str, content: str, sender: Optional[str] = None, recipients: Optional[str] = None, filename: Optional[str] = None, file_content: Optional[Union[str, bytes]] = None, ) -> None: sender = sender or self.mail_sender recipients = recipients or self.mail_recipients message = MIMEMultipart() message["From"] = sender message["To"] = recipients message["Date"] = formatdate(localtime=True) message["Subject"] = subject message.attach(MIMEText(content)) if filename: assert file_content attached_file = MIMEApplication(file_content, Name=filename) attached_file[ "Content-Disposition"] = f'attachment; filename="{filename}"' message.attach(attached_file) server = SMTP(self.mail_server, self.mail_port) if self.mail_use_tls: assert self.mail_username and self.mail_password server.starttls() server.login(self.mail_username, self.mail_password) server.sendmail(sender, recipients, message.as_string()) server.close()
def sendMail(emisor, receptor, psw, nombreimg, ruta_img, ruta_txt): print("Enviando mensaje....") msg = MIMEMultipart() msg['From'] = emisor msg['To'] = receptor msg['Subject'] = nombreimg image = open(ruta_img, "rb") file_txt = open(ruta_txt, "rb") attach_image = MIMEImage(image.read()) attach_txt = MIMEBase("application", "octect-stream") attach_txt.set_payload(file_txt.read()) attach_image.add_header('Content-Disposition', 'attachment; filename = {}.png'.format(nombreimg)) attach_txt.add_header( 'Content-Disposition', 'attachment; filename = {}.txt'.format(msg['Subject'])) msg.attach(attach_image) msg.attach(attach_txt) mailServer = SMTP('smtp.gmail.com', 587) #mailServer.ehlo() mailServer.starttls() #mailServer.ehlo() mailServer.login(msg['From'], psw) mailServer.sendmail(msg['From'], msg['To'], msg.as_string()) mailServer.close() print("Mensaje enviado.")
def send_mail(subject, recipient, body): """ Send an email. """ if config['test']: return True sent = False msg = MIMEText(body + FOOTER_TEXT, 'plain') msg['Subject'] = subject msg['From'] = config['mail_sender'] msg['To'] = recipient conn = None try: conn = SMTP(config['mail_server'], config['mail_port'], timeout=5) conn.set_debuglevel(False) conn.login(config['mail_username'], config['mail_password']) conn.sendmail(msg['To'], [recipient], msg.as_string()) sent = True except: pass finally: if conn: conn.close() return sent
def notify(self, way="email", **msg): #way="email"|"print" '''notify users about running result, currently there are two ways: email, print ''' self.t1 = time.time() data = PAPER+" ends "+str(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(self.t1)))+ \ " TotalN=" + str(CaseTemplate.TotalN) +" SuccessN="+str(CaseTemplate.SuccessN)+ \ " ExistingN="+str(CaseTemplate.ExistingN) +" FailN="+str(CaseTemplate.FailN) data = msg.get("data", data) log.info(data) if way == "print": return TO = msg.get("to", ["*****@*****.**"]) FROM = "*****@*****.**" SMTP_HOST = "smtp.163.com" user= "******" passwords="jiangxiaoke" mailb = ["paper ends", data] mailh = ["From: "+FROM, "To: [email protected]", "Subject: " +data] mailmsg = "\r\n\r\n".join(["\r\n".join(mailh), "\r\n".join(mailb)]) send = SMTP(SMTP_HOST) send.login(user, passwords) rst = send.sendmail(FROM, TO, mailmsg) if rst != {}: self.log.warn("send mail error: "+str(rst)) else: self.log.info("sending mail finished") send.close()
def smtpconnect(password): if service == "smtp": try: smtpco = SMTP(host, port=587) except: resp = 2 return resp try: smtpco.login(username, password) resp = 0 except smtplib.SMTPAuthenticationError: resp = 1 return resp smtpco.close() if service == "smtps": try: smtpco = SMTPS(host, port=465) except: resp = 2 return resp try: smtpco.login(username, password) resp = 0 except smtplib.SMTPAuthenticationError: resp = 1 return resp smtpco.close()
def send_email(subject, msg): with open('../recipients.json') as r: recipients = json.load(r) with open('../gma_secrets.json') as secrets: credentials = json.load(secrets)['smtp'] user = credentials['user'] password = credentials['password'] region = credentials['region'] smtp_server = 'email-smtp.' + region + '.amazonaws.com' smtp_port = 587 sender = '*****@*****.**' text_subtype = 'html' msg = MIMEText(msg, text_subtype) msg['Subject'] = subject msg['From'] = sender msg['To'] = ', '.join(recipients) conn = SMTP(smtp_server, smtp_port) conn.set_debuglevel(1) conn.ehlo() conn.starttls() conn.ehlo() conn.login(user, password) conn.sendmail(sender, recipients, msg.as_string()) conn.close()
def send_mail(send_from, send_to, subject, text, files=[], server="localhost"): from smtplib import SMTP from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(text)) for f in files: part = MIMEBase('application', "octet-stream") part.set_payload( open(f,"rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) smtp = SMTP(server) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def send_msg_list(msgs, sender=None): if len(msgs): connection = SMTP(str(settings.EMAIL_HOST), str(settings.EMAIL_PORT), local_hostname=DNS_NAME.get_fqdn()) try: if (bool(settings.EMAIL_USE_TLS)): connection.ehlo() connection.starttls() connection.ehlo() if settings.EMAIL_HOST_USER and settings.EMAIL_HOST_PASSWORD: connection.login(str(settings.EMAIL_HOST_USER), str(settings.EMAIL_HOST_PASSWORD)) if sender is None: sender = str(settings.DEFAULT_FROM_EMAIL) for email, msg in msgs: try: connection.sendmail(sender, [email], msg) except Exception, e: pass try: connection.quit() except socket.sslerror: connection.close() except Exception, e: pass
def send_email(toaddr, mensaje, settings): """Envía un mensaje por el protocolo SMTP. Los datos del servidor smtp los obtiene de la configuración global, así como el remite que ha de usarse para el mensaje.""" server = settings.email.smtp_server if "no enviar" in server: print("MENSAJE QUE SE ENVIARIA:") print(mensaje) return fromaddr = settings.email.from_addr port = settings.email.smtp_port msg = MIMEText(mensaje, _charset="UTF-8") msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = Header("WeXaM. Reinicio de contraseña", "utf-8") if hasattr(settings.email, "usetls") and settings.email.usetls: print("Conectando con servidor de correo") smtp = SMTP(server, port) smtp.ehlo() print("Conectado. Activando TLS") smtp.starttls() smtp.ehlo() print("Activado. Autentiandose") smtp.login(getattr(settings.email, "user", "anonymous"), getattr(settings.email, "password", "")) print("Autenticado. Enviando mensaje") else: smtp = SMTP(server, port) # smtp.set_debuglevel(1) smtp.sendmail(fromaddr, toaddr, msg.as_string()) smtp.quit() smtp.close()
def sendmails(self, msgs, fromaddr=None): """msgs: list of 2-uple (message object, recipients). Return False if connection to the smtp server failed, else True. """ server, port = self['smtp-host'], self['smtp-port'] if fromaddr is None: fromaddr = '%s <%s>' % (self['sender-name'], self['sender-addr']) SMTP_LOCK.acquire() try: try: smtp = SMTP(server, port) except Exception as ex: self.exception("can't connect to smtp server %s:%s (%s)", server, port, ex) if self.mode == 'test': raise return False for msg, recipients in msgs: try: smtp.sendmail(fromaddr, recipients, msg.as_bytes()) except Exception as ex: self.exception("error sending mail to %s (%s)", recipients, ex) if self.mode == 'test': raise smtp.close() finally: SMTP_LOCK.release() return True
class EmailConnection(object): def __init__(self, username, password): self.username = username self.password = password self.connect() def connect(self): self.connection = SMTP('smtp.gmail.com', 587) self.connection.ehlo() self.connection.starttls() self.connection.ehlo() self.connection.login(self.username, self.password) def send(self, message, from_=None, to=None): if type(message) == str: if from_ is None or to is None: raise ValueError('You need to specify `from_` and `to`') else: from_ = from_ to = to else: from_ = message.email['From'] if 'Cc' not in message.email: message.email['Cc'] = '' to_emails = [message.email['To']] + message.email['Cc'].split(',') to = [complete_email for complete_email in to_emails] message = str(message) return self.connection.sendmail(from_, to, message) def close(self): self.connection.close()
def sendmail(self, destination, subject, message, attach = None): try: msg = MIMEMultipart() msg['From'] = self.username msg['Reply-to'] = self.username msg['To'] = destination msg['Subject'] = subject msg.attach(MIMEText(message)) if attach: part = MIMEBase('application', 'octet-stream') part.set_payload(open(attach, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attach)) msg.attach(part) mailServer = SMTP("smtp.gmail.com", 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() try: mailServer.login(self.username, self.password) mailServer.sendmail(self.username, destination, msg.as_string()) finally: mailServer.close() except Exception, exc: sys.exit("Failed to send mail; %s" % str(exc))
def SendEmail(subject, msgText, to, user,password, alias, imgName, replyTo=None): sender = alias try: conn = SMTP('smtp.gmail.com', 587) msg = MIMEMultipart() msg.attach(MIMEText(msgText, 'html')) msg['Subject']= subject msg['From'] = sender msg['cc'] = to #msg['cc'] = ', '.join(to) if replyTo: msg['reply-to'] = replyTo if imgName != None: fp = open(imgName, 'rb') img = MIMEImage(fp.read(), _subtype="pdf") fp.close() img.add_header('Content-Disposition', 'attachment', filename = imgName) msg.attach(img) conn.ehlo() conn.starttls() conn.set_debuglevel(False) conn.login(user, password) try: conn.sendmail(sender, to, msg.as_string()) finally: conn.close() except: print "Unexpected error:", sys.exc_info()[0]
def sendEmail(to, subject, content): retval = 1 if not(hasattr(to, "__iter__")): to = [to] destination = to text_subtype = 'plain' try: msg = MIMEText(content, text_subtype) msg['Subject'] = subject msg['From'] = sender # some SMTP servers will do this automatically, not all conn = SMTP(host=smtpHost, port=smtpPort) conn.set_debuglevel(True) #conn.login(smtpUsername, smtpPassword) try: if smtpUsername is not False: conn.ehlo() if smtpPort != 25: conn.starttls() conn.ehlo() if smtpUsername and smtpPassword: conn.login(smtpUsername, smtpPassword) else: print("::sendEmail > Skipping authentication information because smtpUsername: %s, smtpPassword: %s" % (smtpUsername, smtpPassword)) conn.sendmail(sender, destination, msg.as_string()) retval = 0 except Exception, e: print("::sendEmail > Got %s %s. Showing traceback:\n%s" % (type(e), e, traceback.format_exc())) retval = 1 finally: conn.close()
def send(self, sender=None, *recipients): mail_config = app.config['email'] if sender == None: sender = mail_config['default_sender'] msg = MIMEText(self.template.render(**self.args)) emails, mimenames = self.addr_process(recipients) msg['Subject'] = self.subject msg['To'] = ", ".join(mimenames) if type(sender) == tuple: msg['From'] = "%s <%s>" % sender sender = sender[1] else: msg['From'] = sender if mail_config.has_key('smtp_port'): s = SMTP(mail_config['smtp_server'], mail_config['smtp_port']) else: s = SMTP(mail_config['smtp_server']) if mail_config['smtp_tls']: s.starttls() s.ehlo() if mail_config.has_key('smtp_pass'): s.login(mail_config['smtp_login'], mail_config['smtp_pass']) s.sendmail(sender, emails, msg.as_string()) s.close()