def sendMail(mailcontent, subject='None'): me = '*****@*****.**' you = '*****@*****.**' # Open a plain text file for reading. For this example, assume that # the text file contains only ASCII characters. #fp = open(textfile, 'rb') ## Create a text/plain message msg = MIMEText(mailcontent) # me == the sender's email address # you == the recipient's email address msg['Subject'] = subject msg['From'] = me msg['To'] = you # Send the message via our own SMTP server, but don't include the # envelope header. s = smtplib.SMTP('localhost') s.sendmail(me, [you], msg.as_string()) s.quit() #print mailcontent logger.debug('Subject: ', subject) logger.warn('Mail content') logger.debug(mailcontent)
def sendmail(config, text): ''' Send an email with the text :param config: dictionary with the fields mail_from, mail_to, mail_host, mail_subject :type config: dict :param text: text to be sent via mail :type text: string ''' if not config.get("mail_to"): Exception("mail_to required!") if not config.get("mail_host"): Exception("mail_host required!") print "sending mail to %s" % config.get("mail_to") msg = MIMEText(text) sender = config.get("mail_from") recipient = config.get("mail_to") msg['Subject'] = config.get("mail_subject") msg['From'] = sender msg['To'] = recipient s = smtplib.SMTP(config.get("mail_host")) s.sendmail(sender, [recipient], msg.as_string()) s.quit()
def send_email(subject='', to_address=[], from_address=from_addr, content=''): """Send an email to a specified user or users This is a basic wrapper around python's STMPLIB library that allows us to send emails to the users in case it's necessary. Any failure of this script is considered fatal. """ try: msg = MIMEText(content) msg['Subject'] = "[{0}] {1} {2}".format(site_domain, subject, date.today().strftime("%Y%m%d")) msg['To'] = EMAIL_SPACE.join(to_address) msg['From'] = from_address logger.debug("All parameters set") mail = smtplib.SMTP(settings.SMTP_SERVER, settings.SMTP_PORT) logger.debug("Instantiated the SMTP") if settings.SMTP_TLS: mail.starttls() logger.debug("Started SMTP TLS connection") mail.login(settings.SMTP_USER, settings.SMTP_PASSWORD) logger.debug("Login success") mail.sendmail(from_addr, to_address, msg.as_string()) logger.debug("Sent email") mail.quit() except Exception as e: logger.error("Email send failed. Error: {0}".format(e))
def mail_reminder(domain, name, email, days_left): global config, verbose, noop, error_log if verbose: print name, email, days_left if not email: error_log.append((domain,name,days_left)) return if days_left.days < 0: error_log.append((domain,name,email,days_left)) return if noop: return return msg = MIMEText("""Hi %s, Your password in the %s domain expires in %s. If you dont know how to fix this, please contact it-support. Best regards Your friendly Password Reminder""" % (name,domain,days_left)) msg["Subject"] = "Password expiring - %s" % domain msg["From"] = "%s <%s>" % (config["mail"]["from_name"], config["mail"]["from_mail"]) msg["To"] = "%s <%s>" % (name, email) s = smtplib.SMTP(config["mail"]["server"]) s.sendmail(msg["From"], [msg["To"]], msg.as_string()) s.quit()
def render_POST(self, request): text = request.args.get("feedback") if text is None: raise FeedbackException("No text.") if len(text) > 50000: raise FeedbackException("Too much text.") text = text[0] # basic checksum to stop really lame kiddies spamming, see feedback.js for js version checksum = 0; text = text.decode("utf-8", "ignore") for x in text: checksum = ((checksum + 1) % 256) ^ (ord(x) % 256); sentchecksum = int(request.args.get("c", [0])[0]) if checksum != sentchecksum: raise FeedbackException("Bad checksum: %d vs. %d" % (sentchecksum, checksum)) msg = MIMEText(text.encode("utf-8"), _charset="utf-8") msg["Subject"] = "qwebirc feedback from %s" % request.getclientIP() msg["From"] = config.feedbackengine["from"] msg["To"] = config.feedbackengine["to"] email = StringIO(msg.as_string()) email.seek(0, 0) factorytype = SMTPSenderFactory factory = factorytype(fromEmail=config.feedbackengine["from"], toEmail=config.feedbackengine["to"], file=email, deferred=defer.Deferred()) reactor.connectTCP(config.feedbackengine["smtp_host"], config.feedbackengine["smtp_port"], factory) self.__hit() return "1"
def smtpSendWithFile(self, toList, sub, att): msg = MIMEMultipart() me = 'Ming<{0}@{1}>'.format(self.mail_user,self.mail_postfix) msg['Subject'] = Header(sub,'utf-8') msg['From'] = me msg['To'] = ','.join(toList) #with open(att,'rb') as fp: # content = MIMEBase('application', 'octet-stream') # content.set_payload(fp.read()) with open(att,'rb') as fp: content = MIMEText(fp.read(), _subtype = 'plain', _charset = 'utf-8') #encoders.encode_base64(content) fileName = '{0}_{1}'.format(sub, os.path.basename(att)) content.add_header('Content-Disposition', 'attachment', filename = fileName) msg.attach(content) composed = msg.as_string() try: s = smtplib.SMTP() s.connect(self.mailHost) s.login(self.mail_user, self.mail_pwd) s.sendmail(me, toList, composed) s.close() return True except Exception as e: print(str(e)) return False #monitor = WinMonitorClass() #content = "This is only a test mail sent by Python. Click following link to go to <a href='http://www.baidu.com'>百度</a>" ##monitor.imapHelper() #mailtoList = [r'*****@*****.**', r'*****@*****.**',r'*****@*****.**'] #if monitor.smtpSend(mailtoList, "Hello SMTP!", content): # print("Send Successfully...") #else: # print("Send Mail Failed!!!")
def send_email(message): message_body = message["message"].encode('utf8') # connect to the smtp server server = smtplib.SMTP('smtp.gmail.com', '587') server.starttls() # Open a file with from_email, password, and to_email. try: with open('email.txt', 'r') as f: content = f.readlines() except FileNotFoundError as err: print(err) # Login password = content[1] from_email = content[0] server.login(from_email, password) msg = MIMEText(message_body) msg['Subject'] = message['Subject'] msg['From'] = from_email # Send a message to_email = content[2] # server.sendmail(from_email, to_email, msg.as_string()) print(msg.as_string()) server.quit()
def process_legal_flag(contact_info, copr): form = forms.CoprLegalFlagForm() legal_flag = models.LegalFlag(raise_message=form.comment.data, raised_on=int(time.time()), copr=copr, reporter=flask.g.user) db.session.add(legal_flag) db.session.commit() send_to = app.config["SEND_LEGAL_TO"] or ["root@localhost"] hostname = platform.node() navigate_to = "\nNavigate to http://{0}{1}".format( hostname, flask.url_for("admin_ns.legal_flag")) contact = "\nContact on owner is: {}".format(contact_info) reported_by = "\nReported by {0} <{1}>".format(flask.g.user.name, flask.g.user.mail) try: msg = MIMEText( form.comment.data + navigate_to + contact + reported_by, "plain") except UnicodeEncodeError: msg = MIMEText(form.comment.data.encode( "utf-8") + navigate_to + contact + reported_by, "plain", "utf-8") msg["Subject"] = "Legal flag raised on {0}".format(copr.name) msg["From"] = "root@{0}".format(hostname) msg["To"] = ", ".join(send_to) s = smtplib.SMTP("localhost") s.sendmail("root@{0}".format(hostname), send_to, msg.as_string()) s.quit() flask.flash("Admin has been noticed about your report" " and will investigate the project shortly.") return flask.redirect(url_for_copr_details(copr))
def send_email(sender,message,receiver,subject): try: msg = MIMEText(message, 'html') msg['Subject'] = subject msg['From']=sender msg['Reply-to'] = 'no-reply' msg['To'] = receiver s = smtplib.SMTP('localhost') s.sendmail(sender, [receiver], msg.as_string()) s.close() except: unknown_error=1 return unknown_error
def notify_problem() : import smtplib from email.mime.text import MIMEText email_body = ''' Dear Admin: Factorbook Motif Pipeline Backend Server stopped running at %s. If this is not intended, please restart the backend server jobs. Note that the last running jobs might be damaged and need to be rerun. Best, Factorbook Motif Pipeline Server '''%ctime() msg = MIMEText( email_body ) # me == the sender's email address me = '*****@*****.**' # you == the recipient's email address you = notify_email msg['Subject'] = 'Factorbook Motif Pipeline Backend Stopped' msg['From'] = me msg['To'] = you # Send the message via our own SMTP server, but don't include the # envelope header. s = smtplib.SMTP('localhost') s.sendmail(me, [you], msg.as_string()) s.quit()
def notify_job_error( jobid ) : import smtplib from email.mime.text import MIMEText email_body = ''' Dear Admin: Factorbook Motif Pipeline Backend Server found a problem while running a job (%s) at %s. The job has been moved to the failed job directory for investigation. Best, Factorbook Motif Pipeline Server '''%(jobid, ctime()) msg = MIMEText( email_body ) # me == the sender's email address me = '*****@*****.**' # you == the recipient's email address you = notify_email msg['Subject'] = 'Factorbook Motif Pipeline Backend Stopped' msg['From'] = me msg['To'] = you # Send the message via our own SMTP server, but don't include the # envelope header. s = smtplib.SMTP('localhost') s.sendmail(me, [you], msg.as_string()) s.quit()
def setUp(self): #set up the image for the message ePic = 'v:/workspace/HandlingEmail_Homework/src/python-logo.png' att = open(ePic, 'rb') img = MIMEImage(att.read()) att.close() img.add_header('Content-Disposition', 'attachment', filename=os.path.basename(ePic)) #set up the message body msgText = MIMEText("This is a test string", 'plain') #build the message msg = MIMEMultipart() msg['To'] = '*****@*****.**' msg['From'] = '*****@*****.**' msg['Subject'] = 'Test Email' msg.attach(msgText) msg.attach(img) self.Mmsg = msg #create a set for comparison self.attachmentSet = {msgText.as_string(), img.as_string()} #engages the function attachments = [ePic] mailObj = emailReturn('*****@*****.**', 'This is a test string', attachments) self.mailTest = mailObj
def make_subpart(content, filename, subtype=None): if subtype is None: subtype = os.path.splitext(filename)[0] msg = MIMEText(content, _subtype=subtype) msg.add_header('Content-Disposition', 'attachment', filename=filename) return msg
def szukaj_brakow(benchmarki, proc_szukane): pck = set(p['cpu'] for p in proc_szukane if p['cpu'] is not None) bek = set(benchmarki) braki = list(sorted(pck - bek)) nieznane = [p['nazwa'] for p in proc_szukane if p['cpu'] is None] if True: tresc = ['Bez benchmarku:'] for cpu in braki: tresc.append('%r' % (cpu,)) if not braki: tresc.append('Nie ma') tresc.extend(['', 'Jest w NewEgg ale nieznany:']) for nazwa, href, params in sorted(nieznane): tresc.append('------------------') tresc.append(nazwa) tresc.append(href) tresc.append(repr(params)) if not nieznane: tresc.append('Brak') tresc = '\n'.join(tresc) import smtplib from email.mime.text import MIMEText msg = MIMEText(tresc) msg['Subject'] = 'Braki procesorow %s' % datetime.datetime.now() msg['From'] = 'kbogus@localhost' msg['To'] = 'kbogus@localhost' s = smtplib.SMTP() s.connect() s.sendmail('kbogus@localhost', ['kbogus@localhost'], msg.as_string()) s.quit()
def send_email(email_type, email_subject, email_message, time): # Email Type: # 1 : Information # 2 : Success # 4 : Error global error_counter try: to = '' #needs to be filled gmail_user = '' #needs to be filled gmail_password = '' #needs to be filled smtpserver = smtplib.SMTP_SSL('smtp.gmail.com',465) smtpserver.ehlo() smtpserver.login(gmail_user, gmail_password) msg = MIMEText(email_message) if email_type == 1: msg['Subject'] = "INFORMATION: "+ str(time)+ " "+email_subject elif email_type == 2: msg['Subject'] = "SUCCESS: "+ str(time)+ " "+email_subject elif email_type == 4: msg['Subject'] = "ERROR: "+ str(time)+ " "+email_subject msg['From'] = gmail_user msg['To'] = to smtpserver.sendmail(gmail_user, [to], msg.as_string()) smtpserver.quit() except Exception, e: print(e) error_counter = 100
def mail_report(to, ticker_name): # Outer wrapper msg_outer = MIMEMultipart() msg_outer['Subject'] = "Stock report for " + ticker_name msg_outer['From'] = "*****@*****.**" msg_outer['To'] = to # Internal text container msg = MIMEMultipart('alternative') text = "Here is the stock report for " + ticker_name html = """\ <html> <head></head> <body> <p>Here is the stock report for <b>""" + ticker_name + """</b> </p> </body> </html> """ part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') # Attach parts into message container. msg.attach(part1) msg.attach(part2) msg_outer.attach(msg) filename = 'stocktracker-GOOG.csv' csv_text = ''.join(file(filename).readlines()) csv_part = MIMEText(csv_text, 'csv') csv_part.add_header('Content-Disposition', 'attachment', filename=filename) msg_outer.attach(csv_part) #send_message(msg_outer) queue_mail(msg_outer)
def _plain_send_mail(sender, recipient, subject, body): header_charset = 'ISO-8859-1' for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8': try: body.encode(body_charset) except UnicodeError: pass else: break sender_name, sender_addr = parseaddr(sender) recipient_name, recipient_addr = parseaddr(recipient) sender_name = str(Header(unicode(sender_name), header_charset)) recipient_name = str(Header(unicode(recipient_name), header_charset)) sender_addr = sender_addr.encode('ascii') recipient_addr = recipient_addr.encode('ascii') msg = MIMEText(body.encode(body_charset), 'plain', body_charset) msg['From'] = formataddr((sender_name, sender_addr)) msg['To'] = formataddr((recipient_name, recipient_addr)) msg['Subject'] = Header(unicode(subject), header_charset) smtp = SMTP(config.get('registration.smtp_host', 'localhost')) if config.get('registration.smtp_login'): try: smtp.starttls() except: pass smtp.login(config.get('registration.smtp_login'), config.get('registration.smtp_passwd')) smtp.sendmail(sender, recipient, msg.as_string()) smtp.quit()
def send_email(subject, message, boarding_pass=None, email=None): if not config["SEND_EMAIL"] or not config["SEND_ADMIN_EMAIL"]: return if email is not None: config["EMAIL_TO"] = email dlog("Sending email to:" + config["EMAIL_TO"]) for to in [string.strip(s) for s in string.split(config["EMAIL_TO"], ',')]: try: smtp = smtplib.SMTP(config["SMTP_SERVER"], config["SMTP_PORT"]) smtp.ehlo() if config["SMTP_USE_TLS"]: smtp.starttls() smtp.ehlo() if config["SMTP_AUTH"]: smtp.login(config["SMTP_USER"], config["SMTP_PASSWORD"]) print 'Sending mail to %s.' % to msg = MIMEMultipart('mixed') msg['Subject'] = subject msg['To'] = to msg['From'] = config["EMAIL_FROM"] msg.attach(MIMEText(message, 'plain')) if boarding_pass: msg_bp = MIMEText(boarding_pass, 'html') msg_bp.add_header('content-disposition', 'attachment', filename='boarding_pass.html') msg.attach(msg_bp) smtp.sendmail(config["EMAIL_FROM"], to, msg.as_string()) print 'Email sent successfully.' smtp.close() except Exception, e: print 'Error sending email!' raise e
def mail(to, subject, text): msg = MIMEText(text) msg["From"] = username msg["To"] = to msg["Subject"] = subject server = smtplib.SMTP("smtp.gmail.com", 587) server.set_debuglevel(1) server.ehlo() server.starttls() server.ehlo() try: server.login(username, passwd) except smtplib.SMTPHeloError as err: print("SMTPHeloError Unexpected error: %s" % err) except smtplib.SMTPAuthenticationError as err: print("SMTPAuthenticationError Unexpected error: %s" % err) except smtplib.SMTPException as err: print("SMTPException Unexpected error: %s" % err) except Exception as err: # if login fails, try again using a manual plain login method print("Unexpected error: %s" % err) server.sendmail(username, to, msg.as_string()) server.close() return "ok"
def __atach_files(self, msg, attachment_files): if isinstance(attachment_files, dict): for f_name, msg_file in attachment_files.items(): ctype, encoding = mimetypes.guess_type(f_name) logging.info("guessing file %s type based on %s", ctype, f_name) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded # (compressed), so use a generic bag-of-bits type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': # Note: we should handle calculating the charset file_part = MIMEText(self.get_content(msg_file), _subtype=subtype) elif maintype == 'image': file_part = MIMEImage(self.get_content(msg_file), _subtype=subtype) elif maintype == 'audio': file_part = MIMEAudio(self.get_content(msg_file), _subtype=subtype) else: file_part = MIMEBase(maintype, subtype) file_part.set_payload(self.get_content(msg_file)) # Encode the payload using Base64 encoders.encode_base64(msg) # Set the filename parameter file_part.add_header('Content-Disposition', 'attachment', filename=f_name) file_part.add_header('Content-Type', ctype, name=f_name) msg.attach(file_part) else: raise Exception('Attachment files should be' 'a dict in format {"filename":"filepath"}')
def send(self,file='', dest='*****@*****.**'): sender = '*****@*****.**' receivers = [dest] try: cli = smtplib.SMTP('smtp.gmail.com', 587) cli.ehlo() cli.starttls() cli.login("*****@*****.**", "konnichiwa") msg = MIMEMultipart() msg['From'] = "Sala Tecnica" msg['Subject'] = "Email Autogenerado - Mantto. Aircon" msg.attach(MIMEText("Se adjunta un archivo con el resultado de las comprobaciones " "del Mantenimiento Mensual Aircon \n para mejor visualizacion de los datos" " abrir el archivo con Excel")) ctype, encoding = mimetypes.guess_type(file) if ctype is None or encoding is not None: ctype = "application/octet-stream" maintype, subtype = ctype.split("/", 1) if maintype == "text": fp = open(file) # Note: we should handle calculating the charset attachment = MIMEText(fp.read(), _subtype=subtype) fp.close() attachment.add_header("Content-Disposition", "attachment", filename=basename(file)) msg.attach(attachment) cli.sendmail(sender,receivers,msg.as_string()) except (socket.gaierror, socket.error, socket.herror, smtplib.SMTPException) as e: print (e)
def send_mail(to_list,sub,content): """ :param to_list: 要发送得邮箱,["*****@*****.**"] :param sub: 主题 :param content: 内容 :return: """ assert not None and isinstance(to_list,list) assert isinstance(sub,str) assert content and isinstance(content,str) _conf=Config_INI('configs/email.ini') _dic_con=_conf.get_fields('hx_zx') mail_host=_dic_con.get('host') #设置服务器 mail_user=_dic_con.get('user') #用户名 mail_password=_dic_con.get('pwd') #口令 mail_postfix=_dic_con.get('postfix') #发件箱的后缀 me="装修之家"+"<"+mail_user+"@"+mail_postfix+">" msg = MIMEText(content,_subtype='plain',_charset='utf-8') msg['Subject'] = sub msg['From'] = me msg['To'] = ";".join(to_list) try: server = smtplib.SMTP() server.connect(mail_host) server.starttls()#启动TLS模式,Gmail要求 server.login(mail_user,mail_password) server.sendmail(me, to_list, msg.as_string()) server.close() return True except Exception, e: return False
def send_email(self, subject, sender, recipients, content): # TODO add crt arg msg = MIMEText(content) msg['Subject'] = subject msg['From'] = sender msg['To'] = ', '.join(recipients) # Send the message via the configured smtp server. # TODO keep same connection during some time ? s = None if self.ssl: s = smtplib.SMTP_SSL(self.host, self.port) else: s = smtplib.SMTP(self.host, self.port) if self.user and self.password: s.login(self.user, self.password) if self.start_tls: s.starttls() s.sendmail(sender, recipients, msg.as_string()) s.quit()
def send_email(msg,subject,me,you, smtp_host,smtp_port=25,encryption="tls", username=None,password=None): DESTINATIONS = you # Import the email modules we'll need from email.mime.text import MIMEText # me == the sender's email address # you == the recipient's email address for dest in DESTINATIONS: msg = MIMEText(msg) msg['Subject'] = subject msg['From'] = me msg['To'] = dest # Send the message via our own SMTP server, but don't include the # envelope header. s = smtplib.SMTP(host=smtp_host,port=smtp_port) s.ehlo() if encryption == "tls": s.starttls() if (not username is None) & (not password is None): s.login(username,password) s.sendmail(me, [dest], msg.as_string()) s.quit()
def send_massage(self, *args, **kwargs): msg_num, content = self._get_message_urls_from_redis() if msg_num <= 0 : print "none messages to send..." return sub = "抓取到%d条高优先级校招信息" % msg_num send_mail_address = SEND_MAIL_USER_NAME + "<" + SEND_MAIL_USER + "@" + SEND_MAIL_POSTFIX + ">" msg = MIMEText(content, 'html', 'utf-8') msg["Accept-Language"]="zh-CN" msg["Accept-Charset"]="ISO-8859-1, utf-8" msg['Subject'] = sub msg['From'] = send_mail_address try: stp = smtplib.SMTP() stp.connect(SEND_MAIL_HOST) # NOTE(Xiyoulaoyuanjia): it get error do not have # it smtplib.SMTPException: SMTP AUTH extension not supported by server stp.starttls() stp.login(SEND_MAIL_USER, SEND_MAIL_PASSWORD) # FIX(Xiyoulaoyuanjia): here if sms get error. do not # send email notification if kwargs['sms']: msg['to'] = to_adress = "139SMSserver<" + RECEIVE_MAIL_USER_139 + "@" + RECEIVE_MAIL_POSTFIX_139 + ">" stp.sendmail(send_mail_address, to_adress, msg.as_string()) if kwargs['email']: msg['to'] = ";".join(RECEIVE_MAIL_LIST) stp.sendmail(send_mail_address, RECEIVE_MAIL_LIST, msg.as_string()) print "send message sucessfully..." self._refresh_message_urls_in_redis() except Exception, e: print "fail to send message: "+ str(e)
def send(smtp_server, from_email, from_name, to_email, subject, body, tls=False, auth=False): msg = MIMEText(body, 'plain', 'utf_8') msg['Subject'] = subject if from_name: msg['From'] = '"{}" <{}>'.format(from_name,from_email) else: msg['From'] = from_email msg['To'] = to_email msg['Date'] = formatdate() if ':' in smtp_server: smtp_hostname, smtp_port = smtp_server.split(':') smtp_port = int(smtp_port) else: smtp_port = 25 smtp_hostname = smtp_server s = smtplib.SMTP() s.connect(smtp_hostname, smtp_port) s.ehlo() if tls: s.starttls() if auth and keyring is not None: passwd = keyring.get_password(smtp_server, from_email) if passwd is None: raise ValueError( 'No password available in ' 'keyring for {}, {}'.format(smtp_server, from_email)) s.login(from_email, passwd) s.sendmail(from_email, [to_email], msg.as_string()) s.quit()
def send_email(mailmsg,mailsubject, to=None): cnf = configRead.cnf sendfrom = cnf['alert_email_from']; sendto = [ cnf['alert_email_to'] ]; # Include extra person if provided if to: sendto.append(to) msg = MIMEText(mailmsg) msg['Subject'] = mailsubject msg['From'] = sendfrom msg['To'] = ','.join(sendto) smtpcnf = cnf['smtp'] port = 25 if 'port' in smtpcnf: port = smtpcnf['port'] s = smtplib.SMTP(smtpcnf['host'], port) if 'username' in smtpcnf: s.login(smtpcnf['username'], smtpcnf['password']) s.sendmail(sendfrom, sendto, msg.as_string()) s.quit()
def user_contactus(): #Setup and start smtp server on the instance (traffic, created) = TrafficModel.objects.get_or_create(created_at=str(datetime.datetime.utcnow()), service="cloud", endpoint="/public/user/contactus") if not created: traffic.interactions += 1 traffic.save() if fk.request.method == 'POST': if fk.request.data: data = json.loads(fk.request.data) try: email = data.get("email", "") message = data.get("message", "") msg = MIMEText("Dear user,\n You contacted us regarding the following matter:\n-------\n%s\n-------\nWe hope to reply shortly.\nBest regards,\n\nDDSM team."%message) msg['Subject'] = 'DDSM -- You contacted us!' msg['From'] = "*****@*****.**" # [email protected] msg['To'] = email msg['CC'] = "*****@*****.**" s = smtplib.SMTP('localhost') s.sendmail("*****@*****.**", email, msg.as_string()) s.quit() return fk.Response('Message sent.', status.HTTP_200_OK) except: print str(traceback.print_exc()) return fk.make_response("Could not send the email.", status.HTTP_503_SERVICE_UNAVAILABLE) else: return fk.make_response("Missing mandatory fields.", status.HTTP_400_BAD_REQUEST) else: return fk.make_response('Method not allowed.', status.HTTP_405_METHOD_NOT_ALLOWED)
def sendnotifymail(cp, package_info, commit): error_details = copy.copy( [package for package in package_info["packages"] if package["name"] == commit.project_name][0]) error_details["logurl"] = "%s/%s" % (cp.get("DEFAULT", "baseurl"), commit.getshardedcommitdir()) error_body = notification_email % error_details msg = MIMEText(error_body) msg['Subject'] = '[delorean] %s master package build failed' % \ commit.project_name email_from = '*****@*****.**' msg['From'] = email_from email_to = error_details['maintainers'] msg['To'] = "packagers" smtpserver = cp.get("DEFAULT", "smtpserver") if smtpserver: logger.info("Sending notify email to %r" % email_to) s = smtplib.SMTP(cp.get("DEFAULT", "smtpserver")) s.sendmail(email_from, email_to, msg.as_string()) s.quit() else: logger.info("Skipping notify email to %r" % email_to)
def sendmail(self, sender_name, sender_email, recipients_list, subject, body, smtp_host, smtp_port): """ Sends an email Parameters ---------- sender_name: string (mandatory) The sender name (ie the database name) sender_email: string (mandatory) The sender email address recipients_list: list of str (mandatory) List of the recipients emails addresses subject: string (mandatory) The email subject body: string (mandatory) The email body smtp_host: string (mandatory) The SMTP server address smtp_port: int (mandatory) The SMTP server port """ msg = MIMEText(body) msg['Subject'] = "[CubicWeb] {0} : {1}".format(sender_name, subject) msg['To'] = ", ".join(recipients_list) s = smtplib.SMTP(smtp_host, smtp_port) s.sendmail(sender_email, recipients_list, msg.as_string()) s.quit()
try: from email.MIMEImage import MIMEImage from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText except ImportError: log.error("hp-scan email destination requires Python 2.2+.") continue msg = MIMEMultipart() msg['Subject'] = email_subject msg['From'] = email_from msg['To'] = ','.join(email_to) msg.preamble = 'Scanned using hp-scan' if email_note: txt = MIMEText(email_note) msg.attach(txt) if file_saved: txt = MIMEText("attached: %s: %dx%d %s PNG image." % (os.path.basename(output), pixels_per_line, lines, scan_mode)) else: txt = MIMEText("attached: %dx%d %s PNG image." % (pixels_per_line, lines, scan_mode)) msg.attach(txt) fp = open(output, 'r') img = MIMEImage(fp.read()) fp.close() if file_saved:
def attach_txt(filename): with open(filename, "r", encoding='utf-8') as f: txt = f.read() msg = MIMEText(txt, _subtype="text") return msg
def send_email(text, subject, to_mail, mail_id=None, in_reply_to=None, project_name=None): # pragma: no cover ''' Send an email with the specified information. :arg text: the content of the email to send :arg subject: the subject of the email :arg to_mail: a string representing a list of recipient separated by a coma :kwarg mail_id: if defined, the header `mail-id` is set with this value :kwarg in_reply_to: if defined, the header `In-Reply-To` is set with this value :kwarg project_name: if defined, the name of the project ''' if not to_mail: return if not pagure.APP.config.get('EMAIL_SEND', True): print '******EMAIL******' print 'To: %s' % to_mail print 'Subject: %s' % subject print 'in_reply_to: %s' % in_reply_to print 'mail_id: %s' % mail_id print 'Contents:' print text.encode('utf-8') print '*****/EMAIL******' return if project_name is not None: subject_tag = project_name else: subject_tag = 'Pagure' if pagure.APP.config['SMTP_SSL']: smtp = smtplib.SMTP_SSL(pagure.APP.config['SMTP_SERVER'], pagure.APP.config['SMTP_PORT']) else: smtp = smtplib.SMTP(pagure.APP.config['SMTP_SERVER'], pagure.APP.config['SMTP_PORT']) for mailto in to_mail.split(','): msg = MIMEText(text.encode('utf-8'), 'plain', 'utf-8') msg['Subject'] = '[%s] %s' % (subject_tag, subject) from_email = pagure.APP.config.get('FROM_EMAIL', '*****@*****.**') msg['From'] = from_email if mail_id: msg['mail-id'] = mail_id msg['Message-Id'] = '<%s>' % mail_id if in_reply_to: msg['In-Reply-To'] = '<%s>' % in_reply_to msg['X-pagure'] = pagure.APP.config['APP_URL'] if project_name is not None: msg['X-pagure-project'] = project_name # Send the message via our own SMTP server, but don't include the # envelope header. msg['To'] = mailto salt = pagure.APP.config.get('SALT_EMAIL') mhash = hashlib.sha512('<%s>%s%s' % (mail_id, salt, mailto)) msg['Reply-To'] = 'reply+%s@%s' % ( mhash.hexdigest(), pagure.APP.config['DOMAIN_EMAIL_NOTIFICATIONS']) try: if pagure.APP.config['SMTP_USERNAME'] \ and pagure.APP.config['SMTP_PASSWORD']: smtp.login(pagure.APP.config['SMTP_USERNAME'], pagure.APP.config['SMTP_PASSWORD']) smtp.sendmail(from_email, [mailto], msg.as_string()) except smtplib.SMTPException as err: pagure.LOG.exception(err) smtp.quit() return msg
#!/usr/bin/python3 from email import encoders from email.header import Header from email.mime.text import MIMEText from email.utils import parseaddr, formataddr import smtplib def _format_addr(s): name, addr = parseaddr(s) return formataddr((Header(name, 'utf-8').encode(), addr)) from_addr = input('From: ') password = input('Password: '******'To: ') smtp_server = input('SMTP server: ') msg = MIMEText('hello, send by Python...', 'plain', 'utf-8') msg['From'] = _format_addr('Python爱好者 <%s>' % from_addr) msg['To'] = _format_addr('管理员 <%s>' % to_addr) msg['Subject'] = Header('来自SMTP的问候……', 'utf-8').encode() server = smtplib.SMTP(smtp_server, 25) server.set_debuglevel(1) server.login(from_addr, password) server.sendmail(from_addr, [to_addr], msg.as_string()) server.quit()
from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import smtplib import os import threading import time keyb = 0 #寄送mail之參數 content = MIMEMultipart() #建立MIMEMultipart物件 content["subject"] = "Bug!!" #郵件標題 content["from"] = "*****@*****.**" #寄件者 content["to"] = "*****@*****.**" #收件者 content.attach(MIMEText("There is an error in the program")) #郵件內容 class waiting(threading.Thread): def newThread(self): Thread(target=self.method).start() def method(self): global keyb keyb = 1 #print(keyb) def main(): menu_all = threading.Thread(target=multifunction) menu_all.start()
# Test mail send sample. import smtplib import email.utils from email.mime.text import MIMEText mailTo = '*****@*****.**' mailFrom = '*****@*****.**' mail = MIMEText('This is the body of the test message.') mail['To'] = mailTo mail['From'] = mailFrom mail['Subject'] = 'Test message' server = smtplib.SMTP('localhost', 8025) server.set_debuglevel(True) try: server.sendmail(mailTo, [mailFrom], mail.as_string()) finally: server.quit()
# @ending: utf-8 @author: JasonChen # @file: email_demo.py @time = 2021/4/30 10:05 # @desc: import email import os import smtplib from email.mime.text import MIMEText email_body = ''' <h1 align ="center">接口自动化测试报告</h1> <p align = "center">详情请查阅附件</p> ''' html_file_path = os.path.join(os.path.dirname(__file__), ) # 只用于界面显示,不会执行发送请求 email_obj = MIMEText(email_body, 'html', 'utf-8') email_obj['from'] = '*****@*****.**' # 发件人 和登录名一致 email_obj['to'] = '*****@*****.**' # 收件人 email_obj['Cc'] = '*****@*****.**' # 抄送人 email_obj['subject'] = 'Qiucy接口自动化报告' # 真的发送邮件请求 smtp = smtplib.SMTP() smtp.connect("smtp.qq.com") # 邮箱的授权码 smtp.login(user='******', password='******') smtp.sendmail("*****@*****.**", "*****@*****.**", email_obj.as_string()) smtp.sendmail("*****@*****.**", ["*****@*****.**", "*****@*****.**"], email_obj.as_string()) smtp.close()
<br/><br/> <h1> Ads insertados por País </h1> {country_data} """.format(category_data = category_html, country_data = country_html) email_host = "" email_user = "" email_password = "" # instantiate a SMTP class email_server = smtplib.SMTP(email_host) # If a user and password is provided, we need to login if(email_user and email_password): email_server.login(email_user, email_password) msg = MIMEMultipart() msg['Subject'] = "Reporte semanal" msg['From'] = "" msg['To'] = "" msg.attach(MIMEImage(open("cat.png", 'rb').read())) msg.attach(MIMEImage(open("country.png", 'rb').read())) msg.attach(MIMEText(content, 'html')) email_server.send_message(msg)
def create_message_with_attachment( sender, to, subject, message_text, file, ): message = MIMEMultipart() message['to'] = to message['from'] = sender message['subject'] = subject msg = MIMEText(message_text) message.attach(msg) (content_type, encoding) = mimetypes.guess_type(file) if content_type is None or encoding is not None: content_type = 'application/octet-stream' (main_type, sub_type) = content_type.split('/', 1) if main_type == 'text': with open(file, 'rb') as f: msg = MIMEText(f.read().decode('utf-8'), _subtype=sub_type) elif main_type == 'image': with open(file, 'rb') as f: msg = MIMEImage(f.read(), _subtype=sub_type) elif main_type == 'audio': with open(file, 'rb') as f: msg = MIMEAudio(f.read(), _subtype=sub_type) else: with open(file, 'rb') as f: msg = MIMEBase(main_type, sub_type) msg.set_payload(f.read()) filename = os.path.basename(file) msg.add_header('Content-Disposition', 'attachment', filename=filename) message.attach(msg) raw_message = \ base64.urlsafe_b64encode(message.as_string().encode('utf-8')) return {'raw': raw_message.decode('utf-8')}
from email.mime.text import MIMEText import sys fromaddr="*****@*****.**" toaddr="*****@*****.**" category=sys.argv[1] respnose=sys.argv[2] msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr if category=="Response Code": msg['Subject'] = "Web Server response error" body = """Web Server script is getting {} code response""".format(respnose) elif category=="Daily Backup" or category=="Web Server": msg['Subject'] = "{} script Failed".format(category) with open(respnose,'r') as file: data = file.read() body = """{} script is failed.\nFollowing are the outputs of {} file.\nErrors are on,\n\n{}\nof the script""".format(category,respnose,data) msg.attach(MIMEText(body, 'plain')) connection = smtplib.SMTP() connection.connect('email-smtp.ap-southeast-1.amazonaws.com',587) connection.starttls() connection.login('AKIAZXI7XNIDH4XUNA56','BKJUpsGvX+Q0RSCoOEo46nWZSTHmoJ+BZ6N0zVykKqQ7') text = msg.as_string() connection.sendmail(fromaddr ,toaddr,text) connection.close()
def email_playbook_report(request): import KUDZU.playbook_report as pr import mimetypes import email import email.mime.application from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import re import smtplib try: pids=request.GET.get('ids') plist = pids.split(',') except Exception as inst: messages.error(request, "Invalid Request parameters") for p in plist: z = None table1 = None table2 = None table3 = None dats = None tiptable1 = None tiptable2 = None allowToSend=True try: playbook = PlayBook.objects.get(playbook_id=p) pml=playbook.uniqueid propname = pml.nametouse mainContact=LogMContactinfo.objects.filter(uniqueid=pml,contact='MC')[0] toEmail=mainContact.personnel.emailaddress fromEmail='*****@*****.**' except Exception as inst: allowToSend=False messages.error(request, "Invalid Property or Contact") if allowToSend==True: try: response = HttpResponse(content_type='application/pdf') styles, HeaderText,tiaalightblue, tiaadarkblue,Gutter,GreenText,LightBlue,DarkRed, highlight, basecolor2, highlightdark, red,llGutter, tsbase, tsupper, tstotal= \ pr.setstyles() filer=pr.runpdf(pml, propname, styles, HeaderText,tiaalightblue, tiaadarkblue,Gutter,GreenText,LightBlue,DarkRed, highlight, basecolor2, highlightdark, red,llGutter, tsbase, tsupper, tstotal) response=pr.createqbr(propname, filer, response,LightBlue,Gutter,'source') propname = propname.replace("\\n", "") propname = re.sub(r'\W+', '', propname) msg = MIMEMultipart() msg['Subject'] = 'Playbook Report' msg['From'] = '*****@*****.**' msg['To'] = toEmail #body = MIMEText("""Here is the updated playbook report""") enQuiryEmail='*****@*****.**' emailContent+='<table width="100%" cellpadding="5">' emailContent+='<tr><td>Dear '+mainContact.personnel.personsname+', <br/><br/>Thank you for updating the Playbook projects for <b>'+pml.nametouse+'</b>. Please find a revised Playbook report attached to this email which incorporates your most recent updates.</td></tr>' emailContent+='<tr><td>If you have any questions or need assistance, please email <a href="mailto:'+enQuiryEmail+'">'+enQuiryEmail+'.</a></td></tr>' emailContent+='</table>' emailContent+='<br/>' emailContent+='<table width="100%" cellpadding="5">' emailContent+='<tr><td>' emailContent+='Thank you,<br/>' emailContent+='The PRPI Team<br/>' emailContent+='<i>on behalf of</i><br/>' emailContent+='<img src="principal.jpg">' emailContent+='</td></tr>' emailContent+='</table>' body = MIMEText(emailContent, 'html') msg.attach(body) filename=propname+".pdf" att = email.mime.application.MIMEApplication(response,_subtype="pdf") att.add_header('Content-Disposition','attachment',filename=filename) msg.attach(att) s = smtplib.SMTP('***************') s.starttls() s.login('***************','***************') s.sendmail(fromEmail,[toEmail], msg.as_string()) s.quit() messages.success(request, "'"+pml.nametouse+ "' playbook report sent to "+toEmail) except Exception as inst: messages.error(request, "unable to send '"+pml.nametouse+ "' playbook report due to: "+str(inst)) return HttpResponseRedirect("/admin/KUDZU/playbook/")
import smtplib from email.mime.text import MIMEText from email.header import Header sender = '*****@*****.**' receivers = ['*****@*****.**'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱 # 三个参数:第一个为文本内容,第二个 plain 设置文本格式,第三个 utf-8 设置编码 message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8') message['From'] = Header("菜鸟教程", 'utf-8') # 发送者 message['To'] = Header("测试", 'utf-8') # 接收者 subject = 'Python SMTP 邮件测试' message['Subject'] = Header(subject, 'utf-8') # qwert12345 try: smtpObj = smtplib.SMTP() smtpObj.connect("smtp.163.com", 25) # 25 为 SMTP 端口号 smtpObj.login("123", "123") smtpObj.sendmail(sender, receivers, message.as_string()) smtpObj.close() print("邮件发送成功") except smtplib.SMTPException as e: print(e) "Error: 无法发送邮件"
import smtplib from email.mime.text import MIMEText receiver = ['*****@*****.**', 'xxx@xxx'] # 设置邮件接收人,这里是我的公司邮箱 host = 'smtp.163.com' # 设置发件服务器地址 port = 25 # 设置发件服务器端口号 sender = '*****@*****.**' # 设置发件邮箱 pwd = 'xxxxxxx' # 设置发件邮箱的密码 body = 'xxxxxxxxxxxxxxxxxxx' # 设置邮件正文,这里是支持HTML的 msg = MIMEText(body, 'html') # 设置正文为符合邮件格式的HTML内容 msg['subject'] = 'content' # 设置邮件标题 msg['from'] = "xxxxxx" # 设置发送人 msg['to'] = ';'.join(receiver) # 设置接收人 s = smtplib.SMTP(host, port) s.login(sender, pwd) # 登陆邮箱 s.sendmail(sender, receiver, msg.as_string()) # 发送邮件
def mailsend(): try: print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))) dayOfWeek = datetime.datetime.now().weekday() if dayOfWeek == 5: print("今天周六,下次邮件在下周一尝试自动推送" ) t = Timer(Dtime11()+86400, mailsend) t.start() elif dayOfWeek == 6: print("今天周日,下次邮件在下周一尝试自动推送" ) t = Timer(Dtime11(), mailsend) t.start() elif select_pdf() is not None and Dtime16_30() < 0 and dayOfWeek != 5 and dayOfWeek != 6: print("今天FMD文件发送时间失效,下次邮件在%d秒后尝试自动推送" % Dtime11()) t = Timer(Dtime11(), mailsend) t.start() elif select_pdf() is None and Dtime16_30() > 0 and dayOfWeek != 5 and dayOfWeek != 6: my_friend = bot.friends().search("胡祥军")[0] my_friend.send(u"这里是微信自动提醒:请留意今天FMD没有完成,下午16:20会再次尝试自动读取文件进行推送。") print("FMD文件不存在,下次邮件在%d秒后尝试自动推送" % Dtime16_20()) time.sleep(Dtime16_20()) if select_pdf() is not None: mailsend() else: t = Timer(Dtime11(), mailsend) t.start() elif select_pdf() is None and Dtime16_30() < 0 and dayOfWeek != 5 and dayOfWeek != 6: print("今天FMD文件发送失败,下次邮件在%d秒后尝试自动推送" % Dtime11()) t = Timer(Dtime11(), mailsend) t.start() elif select_pdf()is not None and dayOfWeek != 5 and dayOfWeek != 6: _user = "******" _pwd = "241007s" _to = "*****@*****.**" #_to = ["*****@*****.**","*****@*****.**"] #for address in _to: # 如名字所示Multipart就是分多个部分 msg = MIMEMultipart() msg["Subject"] = "FMD_"+str(datatoday()) msg["From"] = _user msg["To"] = _to # ---这是文字部分--- part = MIMEText(" This is the automatic push of mail. Please do not reply.") msg.attach(part) # pdf类型附件 part = MIMEApplication(open(select_pdf(), 'rb').read()) part.add_header('Content-Disposition', 'attachment', filename="FMD.pdf") msg.attach(part) s = smtplib.SMTP("s48.cn4e.com", timeout=30) # 连接smtp邮件服务器,端口默认是25 print("连接邮件服务器...") s.login(_user, _pwd) # 登陆服务器 print("登陆邮件服务器成功") strat_time = time.time() s.sendmail(_user, _to, msg.as_string()) # 发送邮件 stop_time = time.time() print("发送邮件成功,耗时%d秒"%(stop_time - strat_time)) s.close() print("下次邮件在%d秒后尝试自动推送" % Dtime11()) t = Timer(Dtime11(), mailsend) t.start() except: print("失败")
s.sendmail(发件人邮箱,收件人邮箱,发送内容) 4.断开连接: s.close() \二、email模块:(负责构建邮件) email模块:支持发送的邮件内容为纯文本、HTML内容、图片、附件。email模块中有几大类来针对不同的邮件内容形式,常用如下: MIMEText:(MIME媒体类型)内容形式为纯文本、HTML页面。 MIMEImage:内容形式为图片。 MIMEMultupart:多形式组合,可包含文本和附件。 每一类对应的导入方式: from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart \三、MIMEText: MIMEText(msg,type,chartset) msg:邮件内容 type:文本类型默认为plain(纯文本),发送HTML格式的时候,修改为html,但同时要求msg的内容也是html的格式。 chartset:文本编码,中文为“utf-8” # 构造TEXT格式的消息 msg = MIMEText("hello.text","plain","utf-8") msg["Subject"] = "xxxxx" msg["From"] = "xxxx" msg["To"] = "xxxx" #发送以上构造的邮件内容要使用as_string将构造的邮件内容转换为string形式。 s.sendmail("xxx","xxx",msg.as_string) \四、MIMEImage、MIMEMultipart: msg = MIMEMultipart() #实例化一个文本对象 msg_sub = MIMEText("hello.text","plain","utf-8")
def _format_addr(s): """ 方法用于 """ name, addr = parseaddr(s) return formataddr((Header(name, 'utf-8').encode(), addr)) # _format_addr('abc') from_addr = '*****@*****.**' # password = '******' # password = '******' password = '******' to_addr = '*****@*****.**' smtp_server = 'smtp.163.com' msg = MIMEText('<html><body><h1>Hello</h1>' + '<p>send by <a href="http://www.python.org">Python</a>...</p>' + '</body></html>', 'html', 'utf-8') msg['From'] = _format_addr('Python爱好者 <%s>' % from_addr) msg['To'] = _format_addr('管理员 <%s>' % to_addr) msg['Subject'] = Header('来自SMTP的问候...', 'utf-8').encode() server = smtplib.SMTP(smtp_server, 25) server.set_debuglevel(1) server.login(from_addr, password) server.sendmail(from_addr, [to_addr], msg.as_string()) server.quit()
def create_message_with_attachment(sender, to, subject, message_text, file, body_type='text'): """Create a message for an email. Args: sender: Email address of the sender. to: Email address of the receiver. subject: The subject of the email message. message_text: The text of the email message. file: The path to the file to be attached. Returns: An object containing a base64url encoded email object. """ message = MIMEMultipart() message['to'] = to message['from'] = sender message['subject'] = subject msg = MIMEText(message_text, body_type) message.attach(msg) print(file) content_type, encoding = mimetypes.guess_type(file) # print(content_type, encoding) if content_type is None or encoding is not None: content_type = 'application/octet-stream' print("*****") main_type, sub_type = content_type.split('/', 1) else: main_type, sub_type = content_type.split('/', 1) print(main_type, sub_type) if main_type in ['text', 'application/pdf', 'pdf']: fp = open(file, 'rb') msg = MIMEText(fp.read(), _subtype=sub_type) fp.close() elif main_type == 'image': fp = open(file, 'rb') msg = MIMEImage(fp.read(), _subtype=sub_type) fp.close() elif main_type == 'audio': fp = open(file, 'rb') msg = MIMEAudio(fp.read(), _subtype=sub_type) fp.close() else: fp = open(file, 'rb') msg = MIMEBase(main_type, sub_type) #msg.add_header("Content-Disposition", filename=file) msg.set_payload(fp.read()) encoders.encode_base64(msg) fp.close() filename = os.path.basename(file) msg.add_header('Content-Disposition', 'attachment', filename=filename) # print(msg) message.attach(msg) text = message.as_string() #.encode('UTF-8').decode('ascii') ## .encode('UTF-8')).decode('ascii') # message.attach(MIMEText(open(file, 'rb').read()), _subtype='pdf') return { "raw": base64.urlsafe_b64encode(text.encode('UTF-8')).decode('ascii') } #{'raw': base64.urlsafe_b64encode(message.as_string())}
import smtplib from email.mime.text import MIMEText from random import randint USERNAME = "******" PASSWORD = "" MAILTO = "" try: server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo() server.starttls() server.ehlo() server.login(USERNAME, PASSWORD) print("success") except: print("failed") for i in range(0,150): #spam msg = MIMEText("Hello Again") msg['Subject'] = ("Sent from Raspberry Pi "+str(randint(0,100000))) msg['From'] = USERNAME msg['To'] = MAILTO server.sendmail(USERNAME, MAILTO, msg.as_string()) print("sent"); if i==149: server.quit()
msg = MIMEMultipart('alternative') msg['Subject'] = email_subject msg['From'] = config['email']['from'] for row in cbg: uniqname = row['SIS Login ID'] raw = uniq_to_raw.get(uniqname, 0) score = uniq_to_grade.get(uniqname, 0) name = row['Student'] name = ' '.join(name.split(',')[::-1]).strip() md = email_body.substitute({ 'name': name, 'raw_grade': raw, 'final_grade': score, }) html = markdown.markdown(md) msg['To'] = uniqname + config['email']['suffix'] #msg['To'] = '*****@*****.**' text_part = MIMEText(md, 'plain') html_part = MIMEText(html, 'html') msg.attach(text_part) msg.attach(html_part) #print(msg.as_string()) sm.sendmail(msg['From'], msg['To'], msg.as_string()) #break
row[0] = period_start row[1] = period_end writer.writerow(row) contents = virtualFile.getvalue() #----------------------# # Send email with CSV file #----------------------# msg = MIMEMultipart() msg['From'] = emailFrom msg['To'] = ', '.join(emailTo) msg['Subject'] = emailSubject emailContent="Dear Sir / Madam,\n\nPlease find the Red Hat OpenShift weekly cluster usage report attached.\n\n" msg.attach(MIMEText(emailContent)) csvFilename = 'openshift_cluster_usage_report_' + lastFriday.strftime('%Y%m%d') + '.csv' part = MIMEBase('application', "octet-stream") part.set_payload(contents) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="{}"'.format(csvFilename)) msg.attach(part) with smtplib.SMTP(smtpHost, port='25') as smtp_server: smtp_server.ehlo() smtp_server.send_message(msg) smtp_server.quit()
def create_message(sender, to, subject, message_text): message = MIMEText(message_text) message["to"] = to message["from"] = sender message["subject"] = subject return {"raw": base64.urlsafe_b64encode(message.as_bytes()).decode()}
def main(): ''' Parse the arguments and send a message. This is an enhanced replacement for mailx in send mode. ''' parser = OptionParser(usage="""\ Send the contents of a directory as a MIME message. Usage: %prog [options] Unless the -o option is given, the email is sent by forwarding to your local SMTP server, which then does the normal delivery process. Your local machine must be running an SMTP server. You can specify a remote SMTP server with optional USER and PASSWORD for authentication """) parser.add_option('-f', '--from', type='string', action='store', metavar='FROM', dest='sender', help='The value of the From: header (required)') parser.add_option('-t', '--to', type='string', action='append', metavar='RECIPIENT', default=[], dest='recipients', help='A To: header value (at least one required)') parser.add_option('-c', '--cc', type='string', action='append', metavar='RECIPIENT', default=[], dest='cc_recipients', help='A CC: header value') parser.add_option('-s', '--subject', type='string', action='store', metavar='SUBJECT', help='Optional subject for this message') parser.add_option('-v', '--verbose', action='store_true', dest='verbose', default=False, help='Provide verbose diagnostics.') group = OptionGroup(parser, "Content Options - at least one required") group.add_option('-D', '--directory', type='string', action='store', metavar='DIRECTORY', default=None, dest='directory', help="""Mail the contents of the specified directory, otherwise don't use a directory. Only the regular files in the directory are sent, and we don't recurse to subdirectories.""") group.add_option('-F', '--file', type='string', action='append', metavar='FILEPATH', default=[], dest='files', help="""Mail the contents of the specified file, otherwise use the directory. Only the regular files in the directory are sent, and we don't recurse to subdirectories.""") group.add_option('-T', '--text', type='string', action='store', metavar='TEXTFILE', default=None, dest='text', help="Mail the contents as the mail text") parser.add_option_group(group) group = OptionGroup(parser, "Delivery Options - optional") group.add_option('-S', '--server', type='string', action='store', metavar='SERVER', default='localhost', help='The server to send the message to') group.add_option('-A', '--anonymous', action='store_true', metavar='ANON', default=False, help='Server connection is anonymous') group.add_option('-U', '--user', type='string', action='store', metavar='USER', default=SMTPUSER, help='Server connection user') group.add_option('-P', '--password', type='string', action='store', metavar='PASSWD', default=SMTPPASS, help='Server connection password') group.add_option('-O', '--output', type='string', action='store', metavar='FILE', help="""Print the composed message to FILE instead of sending the message to the SMTP server.""") parser.add_option_group(group) opts, args = parser.parse_args() if not opts.sender or not opts.recipients: parser.print_help() sys.exit(1) if args: parser.print_help() sys.exit(1) # Create the enclosing (outer) message #if opts.directory or opts.files: outer = MIMEMultipart() #else: #if not opts.text: #outer = MIMENonMultipart('text/rfc822', {}) outer['From'] = opts.sender outer['To'] = COMMASPACE.join(opts.recipients) if opts.cc_recipients: outer['CC'] = COMMASPACE.join(opts.cc_recipients) opts.recipients.extend(opts.cc_recipients) if opts.subject: outer['Subject'] = opts.subject outer.preamble = 'This message is intended for a MIME-aware mail reader.\n' if not opts.directory and not opts.files and not opts.text: print "Enter text - end with EOF (^D):" msg = MIMEText(sys.stdin.read()) outer.attach(msg) if opts.text: #print opts.text with open (opts.text, "r") as fp: msg = MIMEText(fp.read().replace('\n', '\r\n')) outer.attach(msg) if opts.directory: add_directory(outer, opts.directory) if not opts.subject: outer['Subject'] = 'Contents of directory %s' % os.path.abspath(opts.directory) else: if not opts.subject: outer['Subject'] = 'Contents of file(s): %s' % COMMASPACE.join(opts.files) for filename in opts.files: add_file(outer, filename) # Now send or store the message composed = outer.as_string() if opts.output: fp = open(opts.output, 'w') fp.write(composed) fp.close() else: smtp = smtplib.SMTP(opts.server, timeout=60) smtp.set_debuglevel(opts.verbose) if opts.user and opts.password and not opts.anonymous: smtp.starttls() smtp.login(SMTPUSER, SMTPPASS) smtp.sendmail(opts.sender, opts.recipients, composed) smtp.quit()
def patch_to_attachment(self, patch, index): # patches are specifically converted to unicode before entering the db a = MIMEText(patch['body'].encode(ENCODING), _charset=ENCODING) a.add_header('Content-Disposition', "attachment", filename="source patch " + str(index)) return a
# 纯文本 #msg = MIMEText('hello,send by python....','plain','utf-8') #HTML # msg = MIMEText('<html><body><h1>Hello</h1>' + # '<p>send by <a href="http://www.python.org">Python</a>...</p>' + # '</body></html>', 'html', 'utf-8') #附件 msg = MIMEMultipart() msg['From'] = _format_addr('Python爱好者 <%s>' % from_addr) msg['To'] = _format_addr('管理员 <%s>' % to_addr) msg['Subject'] = Header('来自SMTP的问候……', 'utf-8').encode() # 邮件正文是MIMEText: msg.attach(MIMEText('send with file...', 'plain', 'utf-8')) #正文插入图片 # msg.attach(MIMEText('<html><body><h1>Hello</h1>' + # '<p><img src="cid:0"></p>' + # '</body></html>', 'html', 'utf-8')) # 添加附件就是加上一个MIMEBase,从本地读取一个图片: filename = 'cat.jpg' with open(filename, 'rb') as f: # 设置附件的MIME和文件名,这里是png类型: mime = MIMEBase('image', 'png', filename=filename) # 加上必要的头信息: mime.add_header('Content-Disposition', 'attachment', filename=filename) mime.add_header('Content-ID', '<0>') mime.add_header('X-Attachment-Id', '0') # 把附件的内容读进来:
def _mimetext(self, text, subtype='plain'): """Creates a MIMEText object with the given subtype (default: 'plain') If the text is unicode, the utf-8 charset is used. """ charset = self.charset or 'utf-8' return MIMEText(text, _subtype=subtype, _charset=charset)
def createEmail(self, msgdict, builderName, title, results, builds=None, patches=None, logs=None): text = msgdict['body'] type = msgdict['type'] if msgdict.get('subject') is not None: subject = msgdict['subject'] else: subject = self.subject % {'result': Results[results], 'projectName': title, 'title': title, 'builder': builderName} assert '\n' not in subject, \ "Subject cannot contain newlines" assert type in ('plain', 'html'), \ "'{}' message type must be 'plain' or 'html'.".format(type) if patches or logs: m = MIMEMultipart() txt = MIMEText(text, type, ENCODING) m.attach(txt) else: m = Message() m.set_payload(text, ENCODING) m.set_type("text/{}".format(type)) m['Date'] = formatdate(localtime=True) m['Subject'] = subject m['From'] = self.fromaddr # m['To'] is added later if patches: for (i, patch) in enumerate(patches): a = self.patch_to_attachment(patch, i) m.attach(a) if logs: for log in logs: name = "{}.{}".format(log['stepname'], log['name']) if (self._shouldAttachLog(log['name']) or self._shouldAttachLog(name)): # Use distinct filenames for the e-mail summary if self.buildSetSummary: filename = "{}.{}".format(log['buildername'], name) else: filename = name text = log['content']['content'] a = MIMEText(text.encode(ENCODING), _charset=ENCODING) a.add_header('Content-Disposition', "attachment", filename=filename) m.attach(a) # @todo: is there a better way to do this? # Add any extra headers that were requested, doing WithProperties # interpolation if only one build was given if self.extraHeaders: extraHeaders = self.extraHeaders if builds is not None and len(builds) == 1: props = Properties.fromDict(builds[0]['properties']) props.master = self.master extraHeaders = yield props.render(extraHeaders) for k, v in extraHeaders.items(): if k in m: twlog.msg("Warning: Got header " + k + " in self.extraHeaders " "but it already exists in the Message - " "not adding it.") m[k] = v return m
import time import smtplib from email.mime.text import MIMEText # smpt_host = 'smtp.live.com' smtp_host = 'smtp.gmail.com' # smpt_host = 'smtp.mail.yahoo.com # textfile is the name of the program fp = open('email_a_file.py', 'rb') # create a plain text message msg = MIMEText(fp.read()) fp.close() msg['Subject'] = 'email_a_file.py' mail = smtplib.SMTP(smtp_host, 587, timeout=10) mail.set_debuglevel(1) mail.ehlo() mail.starttls() mail.ehlo() mail.login('dxjones00', 'that password')
def send_email(self): '''Zip and send logfiles by email for the specified logger. We use the email settings specified in the .ini file for the logger. ''' self.logger.debug('Initiating log email.') if self.subsettings['Zip']['Enable Zip'] == False: self.mainapp.event_threads[self.loggername].timer_threads['Zip'].task_function() try: self.latest_zip_emailed = "" #in case emaillog doesn't exist. emaillog = open(os.path.join(self.log_full_dir, "_internal_emaillog.txt"), 'r') self.latest_zip_emailed = emaillog.readline() emaillog.close() except: self.logger.debug("Cannot open _internal_emaillog.txt. " "Will email all available zip files.", exc_info=True) self.dir_lock.acquire() try: zipfile_list = os.listdir(self.log_full_dir) # removing elements from a list while iterating over it produces # undesirable results so we make a copy zipfile_list_copy = copy.deepcopy(zipfile_list) self.logger.debug(str(zipfile_list)) if len(zipfile_list) > 0: for filename in zipfile_list_copy: if not self.needs_emailing(filename): zipfile_list.remove(filename) self.logger.debug("removing %s from " "zipfilelist." % filename) self.logger.debug(str(zipfile_list)) # set up the message msg = MIMEMultipart() msg['From'] = self.subsettings['E-mail']['E-mail From'] msg['To'] = COMMASPACE.join(self.subsettings['E-mail']['E-mail To'].split(";")) msg['Date'] = formatdate(localtime=True) msg['Subject'] = self.subsettings['E-mail']['E-mail Subject'] msg.attach(MIMEText(self.subsettings['E-mail']['E-mail Message Body'])) if len(zipfile_list) == 0: msg.attach(MIMEText("No new logs present.")) if len(zipfile_list) > 0: for fname in zipfile_list: part = MIMEBase('application', "octet-stream") part.set_payload(open(os.path.join(self.log_full_dir, fname),"rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(fname)) msg.attach(part) finally: self.dir_lock.release() # set up the server and send the message # wrap it all in a try/except, so that everything doesn't hang up # in case of network problems and whatnot. try: mysmtp = smtplib.SMTP(self.subsettings['E-mail']['SMTP Server'], self.subsettings['E-mail']['SMTP Port']) if self.cmdoptions.debug: mysmtp.set_debuglevel(1) if self.subsettings['E-mail']['SMTP Use TLS'] == True: # we find that we need to use two ehlos (one before and one after starttls) # otherwise we get "SMTPException: SMTP AUTH extension not supported by server" # thanks for this solution go to http://forums.belution.com/en/python/000/009/17.shtml mysmtp.ehlo() mysmtp.starttls() mysmtp.ehlo() if self.subsettings['E-mail']['SMTP Needs Login'] == True: mysmtp.login(self.subsettings['E-mail']['SMTP Username'], myutils.password_recover(self.subsettings['E-mail']['SMTP Password'])) sendingresults = mysmtp.sendmail(self.subsettings['E-mail']['E-mail From'], self.subsettings['E-mail']['E-mail To'].split(";"), msg.as_string()) self.logger.debug("Email sending errors (if any): " "%s \n" % str(sendingresults)) # need to put the quit in a try, since TLS connections may error # out due to bad implementation with # socket.sslerror: (8, 'EOF occurred in violation of protocol') # Most SSL servers and clients (primarily HTTP, but some SMTP # as well) are broken in this regard: # they do not properly negotiate TLS connection shutdown. # This error is otherwise harmless. # reference URLs: # http://groups.google.de/group/comp.lang.python/msg/252b421a7d9ff037 # http://mail.python.org/pipermail/python-list/2005-August/338280.html try: mysmtp.quit() except: pass # write the latest emailed zip to log for the future if len(zipfile_list) > 0: zipfile_list.sort() emaillog = open(os.path.join(self.log_full_dir, "_internal_emaillog.txt"), 'w') emaillog.write(zipfile_list.pop()) emaillog.close() except: self.logger.debug('Error sending email.', exc_info=True) pass # better luck next time
response2 = ser.readlines(50) ser.write("Someone is in the door, http://192.168.1.11/") ser.write(chr(26)) print(response1, " ", response2) ser.close() # Send an email fromEmail = '*****@*****.**' fromEmailPassword = '******' toEmail = '*****@*****.**' msgRoot = MIMEMultipart('related') msgRoot['Subject'] = 'Home Doorbell' msgRoot['From'] = fromEmail msgRoot['To'] = toEmail dt = datetime.now().isoformat() msgText = MIMEText('A person is at the door at :' + dt) msgRoot.attach(msgText) img_data = open('/var/www/html/images/person.jpg', 'rb') msgImage = MIMEImage(img_data.read()) msgImage.add_header('Content-ID', '<person>') msgRoot.attach(msgImage) img_data.close() smtp = smtplib.SMTP('smtp.gmail.com', 587) smtp.starttls() smtp.login(fromEmail, fromEmailPassword) smtp.sendmail(fromEmail, toEmail, msgRoot.as_string()) smtp.quit() print('Email sent..')
echo "<table border=1>" cat /home/fsg/wenchao_auto_mail/yewu/data/Flow_Rates_sub.txt|awk -v a="<tr><td align=center>" -v b="</td><td align=center>" -v c="</td></tr>" -F'\t' '{printf a}''{for(i=1;i<=(NF-1);i++) printf $i b}''{printf $NF c}' echo "</table>" """)%(data_yest)) #发件人,收件人,邮件主题 FROM = '*****@*****.**' TO = ['*****@*****.**'] #收件人 CC=['*****@*****.**'] #抄送人 subject = " 客群监控 - %s " %data_yest # simi_html=a.read() message = MIMEText(simi_html, 'html', 'utf-8') message['Subject'] = Header(subject, 'utf-8') message['From'] = FROM message['TO'] = COMMASPACE.join(TO) message['CC'] = COMMASPACE.join(CC) # 发送邮件 try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(FROM, TO, message.as_string()) print "Bingo" except smtplib.SMTPException: print "Oh~No"