def send_email(to, subject, text, **params): """Send an outgoing email with the given parameters. This function assumes your system has a valid MTA (Mail Transfer Agent) or local SMTP server. This function will first try a local SMTP server and then the system's MTA (/usr/sbin/sendmail) connection refused. :param to: A list of recipient email addresses. :type to: list :param subject: The subject of the email. :type subject: str :param test: The text of the email. :type text: str :param params: An optional set of parameters. (See below) :type params; dict Optional Parameters: :cc: A list of Cc email addresses. :bcc: A list of Cc email addresses. :files: A list of files to attach. :sender: A custom sender (From:). """ # Default Parameters cc = params.get("cc", []) bcc = params.get("bcc", []) files = params.get("files", []) sender = params.get("sender", "root@localhost") recipients = list(chain(to, cc, bcc)) # Prepare Message msg = MIMEMultipart() msg.preamble = subject msg.add_header("From", sender) msg.add_header("Subject", subject) msg.add_header("To", ", ".join(to)) cc and msg.add_header("Cc", ", ".join(cc)) # Attach the main text msg.attach(MIMEText(text)) # Attach any files [msg.attach(mimify_file(filename)) for filename in files] # Contact local SMTP server and send Message try: smtp = SMTP() smtp.connect() smtp.sendmail(sender, recipients, msg.as_string()) smtp.quit() except SocketError as e: if e.args[0] == ECONNREFUSED: p = Popen(["/usr/sbin/sendmail", "-t"], stdin=PIPE) p.communicate(msg.as_string()) else: raise
def do_run(self): while True: try: cycle = self.cycles.get(timeout=1) except ConcurrentEmpty: continue if not self.server.config.mail.enabled: log.debug("Mail is disabled") continue from_addr = self.server.config.operator to_addrs = self.server.config.mail.default_recipients content = self.status_message.render(cycle) if self.server.debug: log.debug("Mail message:\n%s", content) continue smtp = SMTP() smtp.connect() try: smtp.sendmail(from_addr, to_addrs, content) finally: smtp.quit()
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'))
async def trigger_smtp(email: str, subject: str, body: str): """ Sends an email to the mail id of the recipient :param email: the mail id of the recipient :param subject: the subject of the mail :param body: the body of the mail :return: None """ smtp = SMTP(Utility.email_conf["email"]["sender"]["service"], port=Utility.email_conf["email"]["sender"]["port"]) smtp.connect(Utility.email_conf["email"]["sender"]["service"], Utility.email_conf["email"]["sender"]["port"]) if Utility.email_conf["email"]["sender"]["tls"]: smtp.starttls() smtp.login( Utility.email_conf["email"]["sender"]["userid"] if Utility.email_conf["email"]["sender"]["userid"] else Utility.email_conf["email"]["sender"]["email"], Utility.email_conf["email"]["sender"]["password"]) from_addr = Utility.email_conf["email"]["sender"]["email"] msg = "From: %s\nTo: %s\nSubject: %s\n\n\n%s" % (from_addr, email, subject, body) msg = msg.encode('utf-8') smtp.sendmail(from_addr, email, msg) smtp.quit()
def _check_one_mx(smtp: SMTP, error_messages: list, mx_record: str, helo_host: str, from_address: EmailAddress, email_address: EmailAddress) -> bool: """ Check one MX server, return the `is_ambigious` boolean or raise `StopIteration` if this MX accepts the email. """ try: smtp.connect(host=mx_record) smtp.helo(name=helo_host) smtp.mail(sender=from_address.ace) code, message = smtp.rcpt(recip=email_address.ace) smtp.quit() except SMTPServerDisconnected: return True except SocketError as error: error_messages.append(f'{mx_record}: {error}') return False if code == 250: raise StopIteration elif 400 <= code <= 499: # Ambigious return code, can be graylist, temporary problems, # quota or mailsystem error return True message = message.decode(errors='ignore') error_messages.append(f'{mx_record}: {code} {message}') return False
def send_email(self, message): md = markdown.Markdown() from_ = self.config['from'] start = time.time() m = MIMEMultipart('alternative') m['from'] = from_ m['to'] = message['destination'] if message.get('noreply'): m['reply-to'] = m['to'] if 'email_subject' in message: m['subject'] = message['email_subject'] else: m['subject'] = message['subject'] plaintext = None if 'email_text' in message: plaintext = message['email_text'] elif 'body' in message: plaintext = message['body'] if plaintext: mt = MIMEText(None, 'plain', 'utf-8') mt.set_payload(quopri.encodestring(plaintext)) mt.replace_header('Content-Transfer-Encoding', 'quoted-printable') m.attach(mt) # for tracking messages, email_html is not required, so it's possible # that both of the following keys are missing from message html = None if 'email_html' in message: html = message['email_html'] elif 'body' in message: html = md.convert(message['body']) if html: if 'extra_html' in message: html += message['extra_html'] # We need to have body tags for the oneclick buttons to properly parse html = '<body>\n' + html + '\n</body>' mt = MIMEText(None, 'html', 'utf-8') # Google does not like base64 encoded emails for the oneclick button functionalty, # so force quoted printable. mt.set_payload(quopri.encodestring(html)) mt.replace_header('Content-Transfer-Encoding', 'quoted-printable') m.attach(mt) conn = None for mx in self.mx_sorted: try: smtp = SMTP() smtp.connect(mx[1], 25) conn = smtp break except Exception, e: logger.exception(e)
def sendmail(userid, ip, vpnip, vpndate, constatus, connected): smtp = SMTP() smtp.set_debuglevel(1) smtp.connect('MAIL_SERVER_IP', 587) #smtp.login('USERNAME@DOMAIN', 'PASSWORD') from_addr = "Sender-EMAIL-HERE" to_addr = "Recipent-EMAIL-HERE" subj = "VPN01 - A VPN Client has been Detected" strmessage_text = """ A new VPN Client has been detected: UserID: %s IP: %s VPN IP: %s Date: %s Information: %s Verbose OpenVPN Status (Connected Clients): %s """ message = strmessage_text % (userid, ip, vpnip, vpndate, constatus, connected) msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( from_addr, to_addr, subj, vpndate, message) smtp.sendmail(from_addr, to_addr, msg) print "Message successfully sent" smtp.quit()
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 send_mail(self, department): """""" self.configparser.readfp(open(send_info_configfile)) send_info = dict(self.configparser.items(department)) sender = self.loginfo['nickname'] + "<" + self.loginfo[ 'mail_user'] + self.loginfo['mail_postfix'] + ">" msg = MIMEText(content) msg['Subject'] = subject msg['From'] = sender msg['to'] = to_list try: s = SMTP() s.set_debuglevel(1) s.connect(mail_host, 587) #s.ehlo() s.starttls() s.ehlo() #ntlm_authenticate(s, mail_user, mail_pass) s.login(mail_user, mail_pass) s.sendmail(me, to_list, msg.as_string()) s.close() return True except Exception, e: print str(e) return False
def sendErrorMail(): from smtplib import SMTP import datetime import socket localIp = socket.gethostbyname(socket.gethostname()) debuglevel = 0 smtp = SMTP() smtp.set_debuglevel(debuglevel) smtp.connect(smtpHost, smtpPort) smtp.login(smtpUser, smtpPassword) from_addr = "YES Playlist System <*****@*****.**>" to_addr = smtpSendList subj = "ERROR:Playlist file is open - SCRIPT CAN\'T RUN" date = datetime.datetime.now().strftime("%d/%m/%Y %H:%M") message_text = "-------------------------- ERROR -------------------------\n\n" \ "date: %s\n" \ "This is a mail from your YES playlist system.\n\n" \ "On IP: %s\n\n" \ "The file location:\n%s\n\n" \ "Is open and the Rating script can not run!\n" \ "Please close it and RUN THE SCRIPT AGAIN.\n\n" \ "-------------------------- ERROR -------------------------\n\n" \ "Thank you,\nPromotheus" % (date, localIp, playlistFile) msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % (from_addr, to_addr, subj, date, message_text) smtp.sendmail(from_addr, to_addr, msg) smtp.quit()
def _connect(self, tracker): server = SMTP() if self._auth_type=='POP_BEFORE_SMTP': tracker.update(_('Authenticating...')) try: self._pop_account.auth_and_quit() except POPError: tracker.error(_('Error authenticating using POP')) return None try: tracker.update(_('Connecting to server...')) server.connect(self._host, self._port) except: tracker.error(_('Error connecting to %s:%d' % (self._host, self._port))) return None if self._auth_type=='SSL': try: tracker.update(_('Authenticating...')) server.ehlo() server.starttls() server.ehlo() server.login(self._username, self._password) except: tracker.error(_('Error authenticating %s' % self._username)) return None return server
def send_email(self): """Send an outgoing email with the given parameters. This function assumes your system has a valid MTA (Mail Transfer Agent) or local SMTP server. This function will first try a local SMTP server and then the system's MTA (/usr/sbin/sendmail) connection refused. :param to: A list of recipient email addresses. :type to: list :param subject: The subject of the email. :type subject: str :param test: The text of the email. :type text: str :param params: An optional set of parameters. (See below) :type params; dict Optional Parameters: :cc: A list of Cc email addresses. :bcc: A list of Cc email addresses. :files: A list of files to attach. :sender: A custom sender (From:). """ recipients = list(chain(self.to, self.cc, self.bcc)) # Prepare Message msg = MIMEMultipart() msg.preamble = self.subject msg.add_header("From", self.sender) msg.add_header("Subject", self.subject) msg.add_header("To", ", ".join(self.to)) self.cc and msg.add_header("Cc", ", ".join(self.cc)) # Attach the main text msg.attach(MIMEText(self.text)) # Attach any files [msg.attach(self.mimify_file(filename)) for filename in self.files] # Contact local SMTP server and send Message try: smtp = SMTP() smtp.connect() smtp.sendmail(self.sender, recipients, msg.as_string()) Logger.logger.info("Email sent to {0} from {1}.".format( ", ".join(recipients), self.sender)) smtp.quit() except SocketError as e: if e.args[0] == ECONNREFUSED: p = Popen(["/usr/sbin/sendmail", "-t"], stdin=PIPE) p.communicate(msg.as_string()) Logger.logger.debug( "Sending email with Unix's sendmail, smtp feature failed with SockerError" ) else: Logger.logger.error("Failed to send email.") raise
def notify(ip_addr, cable_deltas): import email.mime.text from smtplib import SMTP import socket # make message nameoid = netsnmp.Varbind(".1.3.6.1.2.1.1.6.0") namesw = netsnmp.snmpget( nameoid, Version=2, DestHost=ip_addr, Community=COMMUNITY) msg_items = [u'Подозрения на вырез кабеля: %s по адресу %s\n\n' % (ip_addr, namesw), ] for port, delta in cable_deltas.items(): dloid = netsnmp.Varbind(".1.3.6.1.4.1.171.12.58.1.1.1.8.%s" % port) tekdlina = netsnmp.snmpget( dloid, Version=2, DestHost=ip_addr, Community=COMMUNITY) msg_items.append(u'порт %d: ' % port + u'вырезанная длина %d текущая длина %s\n\n' % (delta, tekdlina[0])) # send email msg = email.mime.text.MIMEText(u''.join(msg_items), 'plain', 'utf-8') msg['Subject'] = u'Подозрения на вырез кабеля' msg['From'] = 'monitoring' msg['To'] = ', '.join(NOTIFICATION['email']) smtp = SMTP() smtp.connect('mail.ru', 25) smtp.login('monitoring', 'password') smtp.sendmail('monitoring@ru', NOTIFICATION['email'], msg.as_string()) smtp.quit()
class EmailService(object): def __init__(self): config = services.get(Config) self._smtp = SMTP() self._host = config.get(self.config_section, "host", "localhost") self._port = config.get(self.config_section, "port", SMTP_PORT) @property def config_section(self): return type(self).__name__ def sendemail(self, email): """ :type email: nxtools.hooks.entities.mail.Email """ mail = MIMEText(email.body, "plain", "UTF-8") mail.add_header("From", email.sender) mail.add_header("To", email.to) mail.add_header("Reply-To", email.reply_to) mail.add_header("Subject", email.subject) self._smtp.connect(self._host, self._port) self._smtp.sendmail(email.sender, email.to, mail.as_string()) self._smtp.quit()
def send_email(to_email,subject,message): # send the message smtp = SMTP() smtp.connect('smtp.mandrillapp.com', 587) smtp.login(os.environ.get('MANDRILL_USERNAME'), os.environ.get('MANDRILL_APIKEY')) from_addr = "Tindfell <*****@*****.**>" to_addr = [to_email] date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" ) Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') msg = MIMEMultipart("alternative") msg['From'] = Header(from_addr.encode('utf-8'), 'UTF-8').encode() msg['To'] = Header(', '.join(to_addr).encode('utf-8'), 'UTF-8').encode() msg['Subject'] = Header(subject.encode('utf-8'), 'UTF-8').encode() msg.attach(MIMEText(message.encode('utf-8'),'plain','utf-8')) #msg.attach(MIMEText(message.encode('utf-8'),'html','utf-8')) io = StringIO() g = Generator(io, False) # second argument means "should I mangle From?" g.flatten(msg) # For Degubbing #print io.getvalue() # send the message! smtp.sendmail(from_addr, to_addr, io.getvalue()) smtp.quit() return
def Check_Server(self,server,port): try: _smtp=SMTP() _smtp.connect(self.server, self.port) return True except: return False
def send_email(defaults, contact, human_friendly_timestamp, message): debuglevel = 0 smtp = SMTP() smtp.set_debuglevel(debuglevel) smtp.connect('localhost', 25) # smtp.login('USERNAME@DOMAIN', 'PASSWORD') from_addr = defaults['smtp_from'] to_addr = "%s <%s>" % (contact['name'], contact['primary_email']) if contact['failsafe_email']: to_addr += ", %s <%s>" % (contact['name'], contact['failsafe_email']) message = """From: %s Organization: %s Subject: credmgr password shard: %s Date: %s To: %s MIME-Version: 1.0 Content-Type: "text/plain; charset=us-ascii" %s """ % (from_addr, defaults['affiliation'], defaults['comment'], human_friendly_timestamp, to_addr, message) smtp.sendmail(from_addr, to_addr, message) smtp.quit()
def send_email(prefs, report_str): recipients = prefs['ADMIN_EMAIL'].split(',') msg = dedent(""" From: %s To: %s Subject: %s Date: %s """).lstrip() % (prefs.get('SMTP_FROM'), prefs.get('ADMIN_EMAIL'), prefs.get('SMTP_SUBJECT'), time.strftime(prefs.get('SMTP_DATE_FORMAT'))) msg += report_str try: smtp = SMTP() if logging.getLogger().isEnabledFor(logging.DEBUG): smtp.set_debuglevel(1) smtp.connect(prefs.get('SMTP_HOST'), prefs.get('SMTP_PORT')) # If the server supports ESMTP and TLS, then convert the message exchange to TLS via the # STARTTLS command. if smtp.ehlo()[0] == 250: if smtp.has_extn('starttls'): (code, resp) = smtp.starttls() if code != 220: raise SMTPResponseException(code, resp) (code, resp) = smtp.ehlo() if code != 250: raise SMTPResponseException(code, resp) else: # The server does not support esmtp. # The Python library SMTP class handles executing HELO/EHLO commands inside # login/sendmail methods when neither helo()/ehlo() methods have been # previously called. Because we have already called ehlo() above, we must # manually fallback to calling helo() here. (code, resp) = self.helo() if not (200 <= code <= 299): raise SMTPHeloError(code, resp) username = prefs.get('SMTP_USERNAME') password = prefs.get('SMTP_PASSWORD') if username and password: smtp.login(username, password) smtp.sendmail(prefs.get('SMTP_FROM'), recipients, msg) debug("sent email to: %s" % prefs.get("ADMIN_EMAIL")) except Exception, e: print "Error sending email" print e print "Email message follows:" print msg
def generate_email_alerter(to_addrs, from_addr=None, use_gmail=False, username=None, password=None, hostname=None, port=25): if not from_addr: from_addr = getuser() + "@" + gethostname() if use_gmail: if username and password: server = SMTP('smtp.gmail.com', 587) server.starttls() else: raise OptionValueError( 'You must provide a username and password to use GMail') else: if hostname: server = SMTP(hostname, port) else: server = SMTP() server.connect() if username and password: server.login(username, password) def email_alerter(message, subject='You have an alert'): server.sendmail( from_addr, to_addrs, 'To: %s\r\nFrom: %s\r\nSubject: %s\r\n\r\n%s' % (", ".join(to_addrs), from_addr, subject, message)) return email_alerter, server.quit
def two_(): while 1: print 'WARNING! sENDING MAIL AFTER 30 SEC' time.sleep(300) if os.path.exists(fil): f=open(fil) i=f.read() f.close() msg = MIMEMultipart() msg['From'] = sub_header msg['To'] = gmail_user msg['Subject'] = currentuser+' , '+sub_header message_content = i msg.attach(MIMEText(str(message_content))) while True: try: mailServer = SMTP() mailServer.connect(server, server_port) mailServer.starttls() mailServer.login(gmail_user,gmail_pwd) mailServer.sendmail(gmail_user, gmail_user, msg.as_string()) mailServer.quit() c=open(fil,'r') lines=c.read() c.close() p = lines[-5:] open(fil,'w').write(p) break except Exception as e: #if verbose == True: print_exc() time.sleep(1)
def _check_mx_records(mx_records: list, smtp_timeout: int, helo_host: str, from_address: str, email_address: str) -> Optional[bool]: 'Check the mx records for a given email address.' smtp = SMTP(timeout=smtp_timeout) smtp.set_debuglevel(debuglevel=0) answers = set() for mx_record in mx_records: try: smtp.connect(host=mx_record) smtp.helo(name=helo_host) smtp.mail(sender=from_address) code, message = smtp.rcpt(recip=email_address) smtp.quit() except SMTPServerDisconnected: answers.add(None) continue except SocketError: answers.add(False) continue if code == 250: return True if 400 <= code <= 499: # Ambigious return code, can be graylist, temporary # problems, quota or mailsystem error answers.add(None) return None if None in answers else False
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 run(self): sub_header = uniqueid if self.jobid: sub_header = 'imp:{}:{}'.format(uniqueid, self.jobid) elif self.checkin: sub_header = 'checkin:{}'.format(uniqueid) msg = MIMEMultipart() msg['From'] = sub_header msg['To'] = gmail_user msg['Subject'] = sub_header message_content = json.dumps({'fgwindow': detectForgroundWindows(), 'sys': getSysinfo(), 'admin': isAdmin(), 'msg': self.text}) msg.attach(MIMEText(str(message_content))) for attach in self.attachment: if os.path.exists(attach) == True: part = MIMEBase('application', 'octet-stream') part.set_payload(open(attach, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="{}"'.format(os.path.basename(attach))) msg.attach(part) while True: try: mailServer = SMTP() mailServer.connect(server, server_port) mailServer.starttls() mailServer.login(gmail_user,gmail_pwd) mailServer.sendmail(gmail_user, gmail_user, msg.as_string()) mailServer.quit() break except Exception as e: #if verbose == True: print_exc() time.sleep(10)
def _send( self ): if not self._mailAddress: gLogger.warn( "No mail address was provided. Mail not sent." ) return S_ERROR( "No mail address was provided. Mail not sent." ) if not self._message: gLogger.warn( "Message body is empty" ) if not self._subject: gLogger.warn( "Subject and body empty. Mail not sent" ) return S_ERROR ( "Subject and body empty. Mail not sent" ) mailString = "From: %s\nTo: %s\nSubject: %s\n%s\n" addresses = self._mailAddress if not type( self._mailAddress ) == type( [] ): addresses = [self._mailAddress] text = mailString % ( self._fromAddress, ', '.join( addresses ), self._subject, self._message ) smtp = SMTP() smtp.set_debuglevel( 0 ) try: #smtp.connect( self._hostname ) smtp.connect() self.sendmail( self._fromAddress, self._mailAddress, text ) except Exception, x: gLogger.error( "Sending mail failed", str( x ) ) return S_ERROR( "Sending mail failed %s" % str( x ) )
def send(self, message, recipients=None): """Send an email. The email is sent to `recipient', which must be a list of RFC2822 compliant mailboxes and groups. If recipients is not specified, it is extracted from the 'To', 'Cc' and 'Bcc' headers of the message. The return value is a list of failed email addresses. If not a single email could be sent, an exception is raised. """ if not isinstance(message, Message): raise TypeError, 'Expecting "Message" instance.' if recipients is None: recipients = message.recipients() recipients += message.cc_recipients() recipients += message.bcc_recipients() message.del_header('Bcc') smtp = SMTP() try: smtp.connect(self.m_smtp_server, self.m_smtp_port) ret = smtp.sendmail(self.m_sender, recipients, message.dump()) except SMTPException, err: m = 'Could not send email: %s' % str(err) raise SendmailError, m
def sendEmail(): msg = "" m = Messages.objects.filter(send=0) e = Forward_Message.objects.filter(enableForward=1) for forward in e: body = '' for message in m: body += message.sndrName + ' left a message on ' + message.date.strftime("%A, %d %B %Y, %I:%M%p") + '\nSubject: ' + message.subject +'\n\n' msg = MIMEText(body, 'plain', 'utf-8') msg['Subject'] = 'Diagoras - New message(s)' try: s = SMTP() s.connect(forward.smtpServer) s.ehlo() s.starttls() s.ehlo() s.login(forward.forwardFrom,forward.passwordFrom) s.sendmail(forward.forwardFrom, forward.forwardTo, msg.as_string()) s.quit() except Exception: msg = Exception; # mark all messages as send Messages.objects.filter(send=0).update(send=1) return msg
def sendEmail(self, botid, jobid, cmd, arg='', attachment=[]): if (botid is None) or (jobid is None): sys.exit("[-] You must specify a client id (-id) and a jobid (-job-id)") sub_header = 'gcat:{}:{}'.format(botid, jobid) msg = MIMEMultipart() msg['From'] = sub_header msg['To'] = gmail_user msg['Subject'] = sub_header msgtext = json.dumps({'cmd': cmd, 'arg': arg}) msg.attach(MIMEText(str(msgtext))) for attach in attachment: if os.path.exists(attach) == True: part = MIMEBase('application', 'octet-stream') part.set_payload(open(attach, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="{}"'.format(os.path.basename(attach))) msg.attach(part) mailServer = SMTP() mailServer.connect(server, server_port) mailServer.starttls() mailServer.login(gmail_user,gmail_pwd) mailServer.sendmail(gmail_user, gmail_user, msg.as_string()) mailServer.quit() print "[*] Command sent successfully with jobid: {}".format(jobid)
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 SuccessEmail(self): ## SEND AN EMAIL TO NOTIFY STAFF debuglevel = 1 smtp = SMTP() smtp.set_debuglevel(debuglevel) smtp.connect('', ) smtp.login('', '') from_addr = "Automated Bot <>" to_addr = "" subj = F'SYNC COMPLETED FOR {name_fn} {name_ln}' date = datetime.now().strftime("%d/%m/%Y %H:%M") message_text = f'Hello,\n\n\ A service request for {name_fn} {name_ln} has been recieved, processed and moved to the following file location:\n\n\ {new_folder}\n\n\n\ The following billing details were entered:\n\ Company: {billing["Company"].values[0]}\n\ Address: {billing["Billing Street 1"].values[0]}, {billing["Billing Street 2"].values[0]}, {billing["Billing City"].values[0]}, {billing["Billing State"].values[0]} {str(billing["Postcode"].values[0])}\n\n\ This task was completed at {datetime.now().strftime("%d/%m/%Y %H:%M:%S")}\n\n\n\ Kind regards,\n\n\ Your Friendly Automated Bot.' msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" \ % ( from_addr, to_addr, subj, date, message_text ) smtp.sendmail(from_addr, to_addr, msg) smtp.quit()
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 ErrorEmail(self): ## SEND AN EMAIL TO NOTIFY STAFF debuglevel = 1 smtp = SMTP() smtp.set_debuglevel(debuglevel) smtp.connect('', ) smtp.login('', '') from_addr = "Automated Bot <>" to_addr = "u" subj = F'ERROR COMPLETING SYNC FOR {name_fn} {name_ln}' date = datetime.now().strftime("%d/%m/%Y %H:%M") message_text = f'Hello,\n\n\ An error has occured while processing the service request for {name_fn} {name_ln}. \n\n\ The Service Request has been moved to the following location:\n\n\ {new_folder}\n\n\n\ Error message:\n\ {error}\n\n\n\ This task was completed at {datetime.now().strftime("%d/%m/%Y %H:%M:%S")}\n\n\n\ Kind regards,\n\n\ Your Friendly Automated Bot.' msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" \ % ( from_addr, to_addr, subj, date, message_text ) smtp.sendmail(from_addr, to_addr, msg) smtp.quit()
def send_email(mail_content_json, mail_to_list=mail_param.mail_to, timeout=10, debuglevel=0, smtp_host=mail_param.mail_smtp_server_host, smtp_port=mail_param.mail_smtp_server_port_tsl, smtp_user=mail_param.mail_smtp_server_user, smtp_passwd=mail_param.mail_smtp_server_pass, mail_from=mail_param.mail_from, issue='99999', issue_name='XXX', new_issue='XXX', new_issue_details='XXX'): smtp = SMTP(timeout=timeout) smtp.set_debuglevel(debuglevel) smtp.connect(smtp_host, smtp_port) smtp.login(smtp_user, smtp_passwd) subj = mail_content_json['subject'] date = datetime.datetime.now().strftime("%d/%m/%Y %H:%M") try: message_text = mail_content_json['content'].format( issue, issue_name, new_issue, new_issue_details) except: message_text = mail_content_json['content'] msg = "From: {0}\nTo: {1}\nSubject: {2}\nDate: {3}\n\n{4}".format( mail_from, mail_to_list, subj, date, message_text) smtp.sendmail(mail_param.mail_from, mail_param.mail_to, msg) smtp.quit()
def WrongVersion(self): ## SEND AN EMAIL TO NOTIFY STAFF ThAT THE DOCUMENT IS NOT THE CORRECT FORMAT debuglevel = 1 smtp = SMTP() smtp.set_debuglevel(debuglevel) smtp.connect('', ) smtp.login('', '') from_addr = "Automated Bot <>" to_addr = "" subj = F'ERROR PARSING {latest_file}' date = datetime.now().strftime("%d/%m/%Y %H:%M") message_text = f'Hello,\n\n\ An error has occured while parsing a the following .docx file: {latest_file}\n\n\n\ Please only place Service Requests with "Latest Form Issued May 2020" under the M2M logo in the Jobber Bot folder\n\n\n\n\n\ This task was completed at {datetime.now().strftime("%d/%m/%Y %H:%M:%S")}\n\n\n\ Kind regards,\n\n\ Your Friendly Automated Bot.' msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" \ % ( from_addr, to_addr, subj, date, message_text ) smtp.sendmail(from_addr, to_addr, msg) smtp.quit()
def reconnect_server(): smtp = SMTP() smtp.connect('mail.xanadu-x.com', 587) smtp.starttls() smtp.login(config["user"], config["pass"]) return smtp
def Check_Server(self, server, port): try: _smtp = SMTP() _smtp.connect(self.server, self.port) return True except: return False
def mandarEmailReserva(request, reserva): from smtplib import SMTP from email.mime.text import MIMEText as text try: sitio = gg_configuracion.objects.get(id=settings.MUNI_ID) email = sitio.email except gg_configuracion.DoesNotExist: sitio = None if not email: email = '*****@*****.**' to_addr = reserva.id_propietario.email if to_addr is None: return '' if to_addr == '': return '' cancha = reserva.id_cancha from_addr = email msg = u'Mail recordatorio de su reserva el día %s.\nCancha: %s - %s .\nTurno: %s hs. a %s hs.\nAnte cualquier inconveniente y/o cancelación comuníquese con Administración.\nAtte. Administración Aires del Llano.' % ( reserva.fecha, cancha, cancha.get_tipo_display(), reserva.hora_inicio.hour, reserva.hora_fin.hour) m = text(msg.encode('utf-8')) m['Subject'] = 'Reserva Canchas (Sistema AutoGestión OnLine)' m['From'] = email m['To'] = to_addr s = SMTP() s.connect('smtp.webfaction.com') s.login(str('grupogua_juanmanuel'), str('qwerty')) s.sendmail(email, to_addr, m.as_string()) message = "Se envío correctamente el email con la reserva." return message
def flush(self): # Add extra newline to info() messages for separation in logfile if not self.buffer: _logger.info("No warnings, no email to send\n") return _logger.info(f"Sending logging email with {len(self.buffer)} records\n") txt = ''.join(self.format(record)+'\n' for record in self.buffer) msg = EmailMessage() msg['Subject'] = "mfaliquot: {}.py has something to say".format(self.scriptname) msg['To'] = ', '.join(self.to_addrs) msg['From'] = self.from_addr msg.set_content("Something went wrong (?) while {}.py was running:\n\n".format(self.scriptname)+txt) try: s = SMTP() s.connect(self.host, self.port) s.starttls() if self.username and self.password: s.login(self.username, self.password) s.send_message(msg) s.quit() except SMTPException as e: _logger.exception("Logging email failed to send:", exc_info=e, extra=self._special_kwarg) except OSError as e: _logger.exception("Some sort of smtp problem:", exc_info=e, extra=self._special_kwarg) except BaseException as e: _logger.exception("Unknown error while attempting to email:", exc_info=e, extra=self._special_kwarg) else: self.buffer.clear()
def on_modified(self, event): if os.path.exists(self.log_file): """Cheque o tamanho do arquivo e remove se for maior que tamnho permitido""" log_size = os.path.getsize(self.log_file) if log_size > self.max_size: print('##############################################') print('log gerado: ', str(datetime.datetime.now())) print('tamanho exedico...') print('enviado notificação...') """ Enviar notificação que o processo de reset do log foi realizado """ debuglevel = 0 smtp = SMTP() smtp.set_debuglevel(debuglevel) smtp.connect('', 587) smtp.login('', 'mmnhbn') from_addr = "" to_addr = "" date = datetime.datetime.now().strftime("%d/%m/%Y %H:%M") message_text = "O log do squid foi removido as: {0}".format(date) subj = "log do squid foi removido " msg = message_text smtp.sendmail(from_addr, to_addr, msg) smtp.quit() print('notificação enviada.... ') print('arquivo deletado....') os.remove(self.log_file) # caso nao seja necessario crear o arquivo, descarte essas duas linhas open(self.log_file, 'w+') print('arquivo criando....')
def send_details_email(req): print "here I am" admin_url = req.POST["admin_url"] landing_url = req.POST["landing_url"] email = req.POST["email_address"] print "here" msg = MIMEMultipart() print "hellop" content = "Admin URL: " + admin_url + "\n" content += "Landing Page URL: " + landing_url msg = MIMEText(content) print "no" msg['Subject'] = "Campaign Details" msg["From"] = "RippleFunction<*****@*****.**>" msg['To'] = email from_addr = '*****@*****.**' to_addrs = [email] print "do I get here" try: s = SMTP() s.connect('smtp.webfaction.com') s.login('mpresh','1564f867') s.sendmail(from_addr, to_addrs, msg.as_string()) return HttpResponse(json.dumps({"status":200} )) except: return HttpResponse(json.dumps({"status":500} ))
def send_email(defaults, contact,human_friendly_timestamp, message): debuglevel = 0 smtp = SMTP() smtp.set_debuglevel(debuglevel) smtp.connect('localhost', 25) # smtp.login('USERNAME@DOMAIN', 'PASSWORD') from_addr = defaults['smtp_from'] to_addr = "%s <%s>" % (contact['name'], contact['primary_email']) if contact['failsafe_email']: to_addr += ", %s <%s>" % (contact['name'], contact['failsafe_email']) message = """From: %s Organization: %s Subject: credmgr password shard: %s Date: %s To: %s MIME-Version: 1.0 Content-Type: "text/plain; charset=us-ascii" %s """ % ( from_addr, defaults['affiliation'], defaults['comment'], human_friendly_timestamp, to_addr, message ) smtp.sendmail(from_addr, to_addr, message) smtp.quit()
def sendEmail(text, jobid='', attachment=[], checkin=False): sub_header = uniqueid if jobid: sub_header = 'imp:{}:{}'.format(uniqueid, jobid) elif checkin: sub_header = 'checkin:{}'.format(uniqueid) msg = MIMEMultipart() msg['From'] = sub_header msg['To'] = gmail_user msg['Subject'] = sub_header message_content = {'FGWINDOW': detectForgroundWindow(), 'SYS': getSysinfo(), 'ADMIN': isAdmin(), 'MSG': text} msg.attach(MIMEText(str(message_content))) for attach in attachment: if os.path.exists(attach) == True: part = MIMEBase('application', 'octet-stream') part.set_payload(open(attach, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="{}"'.format(os.path.basename(attach))) msg.attach(part) while True: try: mailServer = SMTP() mailServer.connect(server, server_port) mailServer.starttls() mailServer.login(gmail_user,gmail_pwd) mailServer.sendmail(gmail_user, gmail_user, msg.as_string()) mailServer.quit() break except Exception as e: #if verbose == True: print_exc() time.sleep(10)
def reply_mail(mail_obj, is_success=True, body=None): print "begin to reply email to [%s] " %(mail_obj["From"] or mail_obj["Reply-To"]) original = mail_obj config = dict(load_config().items("smtp")) smtp = SMTP() smtp.connect('smtp.gmail.com', 587) smtp.starttls() smtp.login(config["user"], config["pass"]) from_addr = "*****@*****.**" to_addr = original["Reply-To"] or parse_base64_mail_mime(original["From"]) subject, encoding = decode_header(original["Subject"])[0] if encoding: subject = subject.decode(encoding) subj = u"Re: " + subject else: subj = u"Re: " + subject date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" ) message_text = "Hello\nThis is a mail from your server\n\nBye\n" if body is not None: msg = u"From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( from_addr, to_addr, subj, date, body.replace('\\n','\n') ) else: msg = u"From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( from_addr, to_addr, subj, date, is_success.replace('\\n','\n') ) smtp.sendmail(from_addr, to_addr, unicode(msg)) smtp.quit() print "replied email to [%s] " %(parse_base64_mail_mime(mail_obj["From"]) or mail_obj["Reply-To"])
def send_two_step_expired_notification(smtp_email, smtp_password, \ smtp_host, smtp_port, smtp_no_tls, to_addr): print("Sending two_step_expired notification via email...") smtp = SMTP() smtp.set_debuglevel(0) smtp.connect(smtp_host, smtp_port) if not smtp_no_tls: smtp.starttls() smtp.login(smtp_email, smtp_password) subj = "icloud_photos_downloader: Two step authentication has expired" date = datetime.datetime.now().strftime("%d/%m/%Y %H:%M") message_text = """Hello, Just letting you know that two-step authentication has expired for the icloud_photos_downloader script. Please log in to your server and update two-step authentication. """ from_addr = "iCloud Photos Downloader <" + smtp_email + ">" msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( from_addr, to_addr, subj, date, message_text) smtp.sendmail(smtp_email, to_addr, msg) smtp.quit()
def _send(self): if not self._mailAddress: gLogger.warn("No mail address was provided. Mail not sent.") return S_ERROR("No mail address was provided. Mail not sent.") if not self._message: gLogger.warn("Message body is empty") if not self._subject: gLogger.warn("Subject and body empty. Mail not sent") return S_ERROR("Subject and body empty. Mail not sent") mail = MIMEText(self._message, "plain") addresses = self._mailAddress if not type(self._mailAddress) == type([]): addresses = [self._mailAddress] mail["Subject"] = self._subject mail["From"] = self._fromAddress mail["To"] = ', '.join(addresses) smtp = SMTP() smtp.set_debuglevel(0) try: smtp.connect() smtp.sendmail(self._fromAddress, addresses, mail.as_string()) except Exception, x: return S_ERROR("Sending mail failed %s" % str(x))
def on_modified(self, event): if os.path.exists(self.log_file): """Cheque o tamanho do arquivo e remove se for maior que tamnho permitido""" log_size = os.path.getsize(self.log_file) if log_size > self.max_size: print('##############################################') print('log gerado: ', str(datetime.datetime.now())) print('tamanho exedico...') print('enviado notificação...') """ Enviar notificação que o processo de reset do log foi realizado """ debuglevel = 0 smtp = SMTP() smtp.set_debuglevel(debuglevel) smtp.connect('', 587) smtp.login('', 'mmnhbn') from_addr = "" to_addr = "" date = datetime.datetime.now().strftime("%d/%m/%Y %H:%M") message_text = "O log do squid foi removido as: {0}".format( date) subj = "log do squid foi removido " msg = message_text smtp.sendmail(from_addr, to_addr, msg) smtp.quit() print('notificação enviada.... ') print('arquivo deletado....') os.remove(self.log_file) # caso nao seja necessario crear o arquivo, descarte essas duas linhas open(self.log_file, 'w+') print('arquivo criando....')
def email(content, format): ''' @summary: send email to manager @param content: email content @param format: html or plain ''' try: msg = MIMEText(content, format) msg['From'] = Header('{0} <{1}>'.format( search('(\w+)@', MAIL_SENDER).group(1), MAIL_SENDER)) msg['To'] = Header(';'.join([ '{0} <{1}>'.format(search('(\w+)@', r).group(1), r) for r in MAIL_RECVERS ])) msg['Subject'] = Header(MAIL_SUBJECT) smtp = SMTP() smtp.connect(SMTP_HOST, SMTP_PORT) smtp.login(MAIL_SENDER, MAIL_PASSWD) smtp.sendmail(MAIL_SENDER, MAIL_RECVERS, msg.as_string()) log.debug('send email to %s success', msg['To']) except SMTPException as e: exception(e, 'send email failed, %s' % str(e)) finally: if smtp is not None: smtp.quit()
def send_mail(self, text, subj='AD to Tableau server synchronization error.'): self.logger.debug( f'Send mail. mail_to: {self.send_to}, mail_from: {self.mail_from}') msg = MIMEMultipart() msg['From'] = self.mail_from msg['To'] = self.send_to msg['Subject'] = subj body = text msg.attach(MIMEText(body, 'plain')) server = SMTP() text = msg.as_string() if isinstance(self.send_to, str): self.send_to = [m.strip() for m in self.send_to.split(',')] if self.noop: try: server.connect() except Exception as e: self.logger.error(e) return try: server.sendmail(self.mail_from, self.send_to, text) except Exception as e: self.logger.error(e) return finally: server.quit() else: self.logger.info("NOOP is True. Mail didn't send") self.logger.info(f"subj: {subj}") self.logger.info(f"text: {text}")
def _send( self ): if not self._mailAddress: gLogger.warn( "No mail address was provided. Mail not sent." ) return S_ERROR( "No mail address was provided. Mail not sent." ) if not self._message: gLogger.warn( "Message body is empty" ) if not self._subject: gLogger.warn( "Subject and body empty. Mail not sent" ) return S_ERROR ( "Subject and body empty. Mail not sent" ) mail = MIMEText( self._message , "plain" ) addresses = self._mailAddress if not type( self._mailAddress ) == type( [] ): addresses = [self._mailAddress] mail[ "Subject" ] = self._subject mail[ "From" ] = self._fromAddress mail[ "To" ] = ', '.join( addresses ) smtp = SMTP() smtp.set_debuglevel( 0 ) try: smtp.connect() smtp.sendmail( self._fromAddress, addresses, mail.as_string() ) except Exception, x: return S_ERROR( "Sending mail failed %s" % str( x ) )
def my_send_mail(subject, txt, sender, to=[], files=[], charset='UTF-8'): import os from django.core.mail import send_mail from email import Encoders from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from django.conf import settings from django.core.mail import EmailMultiAlternatives for dest in to: dest = dest.strip() msg = MIMEMultipart('related') msg['Subject'] = subject msg['From'] = sender msg['To'] = dest msg.preamble = 'This is a multi-part message in MIME format.' msgAlternative = MIMEMultipart('alternative') msg.attach(msgAlternative) msgAlternative.attach(MIMEText(txt, _charset=charset)) msgAlternative.attach(MIMEText(txt, 'html', _charset=charset)) #msg.attach_alternative(txt, "text/html") 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) from smtplib import SMTP smtp = SMTP() smtp.connect(host=settings.EMAIL_HOST) smtp.sendmail(sender,dest, msg.as_string()) smtp.quit()
def sendEmail(self, botid, jobid, cmd, arg='', attachment=[]): if (botid is None) or (jobid is None): sys.exit("[-] You must specify a client id (-id) and a jobid (-job-id)") sub_header = 'gdog:{}:{}'.format(botid, jobid) msg = MIMEMultipart() msg['From'] = sub_header msg['To'] = gmail_user msg['Subject'] = sub_header msgtext = json.dumps({'cmd': cmd, 'arg': arg}) msg.attach(MIMEText(str(infoSec.Encrypt(msgtext)))) for attach in attachment: if os.path.exists(attach) == True: part = MIMEBase('application', 'octet-stream') part.set_payload(open(attach, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="{}"'.format(os.path.basename(attach))) msg.attach(part) mailServer = SMTP() mailServer.connect(server, server_port) mailServer.starttls() mailServer.login(gmail_user,gmail_pwd) mailServer.sendmail(gmail_user, gmail_user, msg.as_string()) mailServer.quit() print "[*] Command sent successfully with jobid: {}".format(jobid)
def send_mail_with_img(self,filepath): try: smtp = SMTP() smtp.connect("smtp.163.com") smtp.login(self.smtp_username, self.smtp_password) # 构造MIMEMultipart对象做为根容器 main_msg = MIMEMultipart('related') msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.<br><img src="cid:{image}"><br>liming.li!'.format(image=os.path.basename(filepath)), 'html') main_msg.attach(msgText) # 构造附件1 att1 = MIMEImage(open(filepath, 'rb').read()) att1.add_header("Content-ID", '<{image}>'.format(image=os.path.basename(filepath))) main_msg.attach(att1) # 设置根容器属性 main_msg['From'] = self.smtp_sender main_msg['To'] = self.smtp_receiver main_msg['Subject'] = "attach test" main_msg['Date'] = formatdate() # 得到格式化后的完整文本 fullText = main_msg.as_string() # 用smtp发送邮件 send_mail_flag = smtp.sendmail(self.smtp_sender, self.smtp_receiver, fullText) if send_mail_flag: print("\n邮件发送失败") else: print("\n邮件发送成功") smtp.quit() except: traceback.print_exc()
def notify_unban(to_addr, host, port, user, unbanned, released=False, deleted=False): if (not unbanned) and (isinstance(released, bool) and not released) and (isinstance(deleted, bool) and not deleted): return False hostname = socket.gethostname() smtp = SMTP() smtp.connect(host, port) from_addr = "pcc@" + hostname countrylist = [] subj = "" message_text = "" if unbanned: subj = "User ban release (%s)" % user message_text = "User %s has been unbanned on %s by an administrador\n" % (user, hostname) else: subj = "Messages on hold messages managed" message_text = "Messages on hold on %s have been managed by an administrator\n" % (hostname) if not isinstance(released, bool): message_text += "Released mails: %d\n" % (released) if not isinstance(deleted, bool): message_text += "Deleted mails: %d\n" % (deleted) msg = "From: %s\nTo: %s\nSubject: %s\n\n%s" % (from_addr, to_addr, subj, message_text) smtp.sendmail(from_addr, to_addr, msg)
def send_mail(self, content): # 普通的邮件 try: smtp = SMTP() smtp.connect(self.smtp_smtpserver) smtp.login(self.smtp_username, self.smtp_password) # 构造MIMEMultipart对象做为根容器 main_msg = MIMEMultipart('alternative') # 构造MIMEText对象做为邮件正文并附加到根容器 text_msg = MIMEText(content+"\r\n",'text','utf-8') #content必须已\r\n区分邮件头和正文,以html格式最佳 #main_msg.attach(text_msg) html_msg = MIMEText( '<html><body><h4>hello world!</h4></body></html>', 'html' ) main_msg.attach(html_msg) # 设置根容器属性 main_msg['From'] = self.smtp_sender main_msg['To'] = self.smtp_receiver main_msg['Subject'] = "attach test" main_msg['Date'] = formatdate() # 得到格式化后的完整文本 fullText = main_msg.as_string() # 用smtp发送邮件 send_mail_flag = smtp.sendmail(self.smtp_sender, self.smtp_receiver, fullText) if send_mail_flag: print("\n邮件发送失败") else: print("\n邮件发送成功") smtp.quit() except: traceback.print_exc()
def generate_email_alerter(to_addrs, from_addr=None, use_gmail=False, username=None, password=None, hostname=None, port=25): if not from_addr: from_addr = getuser() + "@" + gethostname() if use_gmail: if username and password: server = SMTP('smtp.gmail.com', 587) server.starttls() else: raise OptionValueError('You must provide a username and password to use GMail') else: if hostname: server = SMTP(hostname, port) else: server = SMTP() server.connect() if username and password: server.login(username, password) def email_alerter(message, subject='SiteWatcher: You have an alert!'): server.sendmail(from_addr, to_addrs, 'To: %s\r\nFrom: %s\r\nSubject: %s\r\n\r\n%s' % (", ".join(to_addrs), from_addr, subject, message)) return email_alerter, server.quit
def myMessage(request): form = MessageForm(request.POST or None) context = {'form':form} template = 'message/monMessage.html' if form.is_valid(): # print(form.cleaned_data) titre = form.cleaned_data['titre'] auteur = form.cleaned_data['auteur'] contenu = form.cleaned_data['contenu'] sujet = form.cleaned_data['sujet'] email = form.cleaned_data['mail'] form.save() from_addr = '*****@*****.**' to_addrs = ['*****@*****.**'] msg = "Vous avez recu un nouveau message : \n" + "auteur : " + auteur + "\n" + "titre : " \ + titre + "\n" + "sujet : " + sujet + "\n" + "contenu : " + contenu + "\n" msg.encode('utf-8') s = SMTP() s.connect('smtp.webfaction.com') s.login('istarosel','igor1975staroseltsev') s.sendmail(from_addr, to_addrs, msg) messages.success(request, 'Votre mail a été envoyé') return render(request,template,context)
def send_report_after_ran_test(): """根据 config 中的配置信息,在完成测试后通过邮件方式发送 HTML 格式报告给相关人 Args: None. return: None. raise: None. """ msg = MIMEMultipart() msg['subject'] = u"软件测试报告" msg['from'] = config.email_sender msg['to'] = config.email_reciver url = "http://" + config.report_server_name + ":" + config.report_server_port + "/report/" \ + os.path.split(config.report_dir)[1] + '/summary_report.html' print_debug_info("the report's url is: " + url) report_content = MIMEText(urllib2.urlopen(url).read().decode('utf-8'), 'html') msg.attach(report_content) print_debug_info("report attached.") try: smtp = SMTP() smtp.connect(config.smtp_server_name, config.smtp_server_port) smtp.login(config.smtp_username, config.smtp_password) smtp.sendmail(config.email_sender, config.email_reciver, \ msg.as_string()) print_debug_info("report has already sent.") smtp.quit() except Exception, e: raise e
def send_email(to, subject, text, **params): # Default Parameters cc = params.get("cc", []) bcc = params.get("bcc", []) files = params.get("files", []) sender = params.get("sender", "root@localhost") recipients = list(chain(to, cc, bcc)) # Prepare Message msg = MIMEMultipart() msg.preamble = subject msg.add_header("From", sender) msg.add_header("Subject", subject) msg.add_header("To", ", ".join(to)) cc and msg.add_header("Cc", ", ".join(cc)) # Attach the main text msg.attach(MIMEText(text)) # Attach any files [msg.attach(mimify_file(filename)) for filename in files] # Contact local SMTP server and send Message try: smtp = SMTP() smtp.connect() smtp.sendmail(sender, recipients, msg.as_string()) smtp.quit() except SocketError as e: if e.args[0] == ECONNREFUSED: p = Popen(["/usr/sbin/sendmail", "-t"], stdin=PIPE) p.communicate(msg.as_string()) else: raise