def send_message(self, data, threadId=None): service = self.get_service() message = MIMEText(data['message'], 'html') message['to'] = data['to'] message['from'] = data['from'] message['subject'] = data['subject'] if data.get('threadId', None) is None: raw = base64.urlsafe_b64encode(message.as_bytes()).decode() email = service.users().messages().send(userId='me', body={ 'raw': raw }).execute() return { "message_id": email['id'], "thread_id": email['threadId'], 'email_type': email['labelIds'] } else: message.add_header('References', data['References']) message.add_header('In-Reply-To', data['In-Reply-To']) raw = base64.urlsafe_b64encode(message.as_bytes()).decode() email = service.users().messages().send(userId='me', body={ 'raw': raw, 'threadId': data['threadId'] }).execute() return { "message_id": email['id'], "thread_id": email['threadId'], 'email_type': email['labelIds'] }
def mime_msg(sender, receivers, dkim_selector, dkim_key, service_ip, title=None): # type: (str, str, str, str, str, str) -> str if title is None: title = rand_title() domain = sender.split('@')[1] fh = open(dkim_key) dkim_key = fh.read() fh.close() content = open('templates/type_1.html', encoding='utf-8') message = MIMEText(content.read(), _subtype='html', _charset='utf-8') content.close() message['Accept-Language'] = "zh-CN" message['Accept-Charset'] = "ISO-8859-1,UTF-8" message['From'] = encode_header(rand_from(), sender) message['To'] = encode_header(rand_to(), receivers) message['Subject'] = Header(title, 'utf-8') message[ 'Received'] = f'from msc-channel180022225.sh({service_ip}) by mail.{domain}(127.0.0.1);' message['Message-ID'] = uuid.uuid4().__str__() message['MIME-Version'] = '1.0' message['Return-Path'] = f'mail.{domain}' signature = dkim.sign( message=message.as_bytes(), selector=bytes(dkim_selector, encoding='utf-8'), domain=bytes(domain, encoding='utf-8'), privkey=bytes(dkim_key, encoding='utf-8'), ) message['DKIM-Signature'] = bytes.decode( signature.lstrip(b"DKIM-Signature: ")) return message.as_bytes()
def create_message(sender, to, subject, message_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. Returns: An object containing a base64url encoded email object. """ message = MIMEText(message_text) print(message) message['to'] = to message['from'] = sender message['subject'] = subject print(message.as_bytes()) # return {'raw': base64.urlsafe_b64encode(message.as_string())} rawasbytes = base64.urlsafe_b64encode(message.as_bytes()) print(rawasbytes) rawcontent = rawasbytes.decode() print(rawcontent) return {"raw": rawcontent}
def createMessage(self, sender, to, subject, message_text): """ Creates a MIME fromat email message """ message = MIMEText(message_text) message['to'] = to message['from'] = sender message['subject'] = subject return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}
def create_message(message_text): message = MIMEText(message_text) message['to'] = '<sender>' message['from'] = '<receiver>' message['subject'] = 'Test email' encoded_message = base64.urlsafe_b64encode(message.as_bytes()) return {'raw': encoded_message.decode()}
def send_mail(Subject, Message, From, To, From_name=None, To_name=None): message_text = MIMEText(Message) if To_name: message_text['to'] = formataddr( (str(Header(To_name, 'utf-8')), To)) else: message_text['to'] = To if From_name: message_text['from'] = formataddr( (str(Header(From_name, 'utf-8')), From)) else: message_text['from'] = From message_text['subject'] = Subject message = {'raw': base64.urlsafe_b64encode(message_text.as_bytes()).decode()} credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1', http=http) try: message = (service.users().messages().send(userId=From, body=message) .execute()) print('Message Id: %s' % message['id']) return message except errors.HttpError as error: print('An error occurred: %s' % error)
def main(): """ Shows basic usage of the Gmail API. Creates a Gmail API service object and outputs a list of label names of the user's Gmail account. """ credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1', http=http) results = service.users().labels().list(userId='me').execute() labels = results.get('labels', []) if not labels: print('No labels found.') else: print('Labels:') for label in labels: print(label['name']) # Create a message message = MIMEText('This is another test.') message['to'] = '*****@*****.**' message['from'] = '*****@*****.**' message['subject'] = 'GMail API Test Message' raw_message = {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()} # Attempt to send a message email = (service.users().messages().send(userId='me', body=raw_message).execute()) print('Message ID: %s' % email['id'])
def send_email(self, subject='', html='', send_to=(Config.MAIL_GMAIL, )): # if exception: # _, _, tb = sys.exc_info() # traceback.print_tb(tb) # tb_info = traceback.extract_tb(tb) # filename_, line_, func_, text_ = tb_info[-1] # message = 'An error occurred on File "{file}" line {line}\n {assert_message}'.format( # line=line_, assert_message=exception.args, file=filename_) # text = message # if template: # text = render_template(template + '.html', **kwargs) # msg = MIMEText(text, 'html') # else: # msg = MIMEText(text, 'plain') msg = MIMEText(html, 'html') msg['Subject'] = subject msg['From'] = self.username msg['To'] = ','.join(send_to) server = smtplib.SMTP(Config.MAIL_SERVER) server.starttls() server.login(self.username, self.password) server.sendmail(self.username, send_to, msg.as_bytes()) server.quit()
def mensaje_a_enviar(self, email_to, text, subject): message = MIMEText(text) message['to'] = email_to message['from'] = self.email_from message['subject'] = subject message_decode = base64.urlsafe_b64encode(message.as_bytes()).decode('utf-8') return({'raw': message_decode})
def send_email(service, report_messages, count): digest = '<html><head></head><body>' indox_messages = report_messages.pop('Inbox', None) if indox_messages: digest += digest_str('Inbox', indox_messages) + '<br>' for label, subjects in report_messages.items(): digest += digest_str(label, subjects) digest += '<a href="https://mail.google.com/mail/u/1/#inbox">Open</a><br><br>/eom</body></html>' date = datetime.now() message = MIMEText(digest, 'html') message['to'] = secrets.TO_EMAIL message['from'] = secrets.FROM_EMAIL message['subject'] = 'NU {}/{} Digest ({} Unread)'.format( date.month, date.day, count) encoded = base64.urlsafe_b64encode(message.as_bytes()) message_body = {'raw': encoded.decode()} try: service.users().messages().send(userId='me', body=message_body).execute() except errors.HttpError as error: print(error)
def create_message(to, subject, personalizedPath, cc=None): """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. personalizedPath: File path to email in html file with variable replaced with proper values. Returns: An object containing a base64url encoded email object. """ f = open(personalizedPath, 'r') message_text = f.read() sender = self.__mentor_cred._subject message = MIMEText(message_text, 'html') message['to'] = to message['cc'] = cc message['from'] = sender message['subject'] = subject # the message should converted from string to bytes. message_as_bytes = message.as_bytes() # encode in base64 (printable letters coding) message_as_base64 = base64.urlsafe_b64encode(message_as_bytes) raw = message_as_base64.decode() # need to JSON serializable return {'raw': raw}
def create_message(to, subject, message_text): message = MIMEText(message_text) message['to'] = to message['subject'] = subject b64_bytes = base64.urlsafe_b64encode(message.as_bytes()) b64_string = b64_bytes.decode() return {'raw': b64_string}
def create_message(sender, to, subject, message_text): """ Create a message for an email. Parameters ---------- sender : str Email address of the sender. to : str Email address of the receiver. subject : str The subject of the email message. message_text : str The text of the email message. Returns ------- object An object containing a base64url encoded email object. """ message = MIMEText(message_text) message['to'] = to message['from'] = sender message['subject'] = subject b64_bytes = base64.urlsafe_b64encode(message.as_bytes()) b64_string = b64_bytes.decode() return {'raw': b64_string}
def send_email(self, email, selected_cluster, ca_cert, server_ip): """ This function can be used to send emails from an internal account at CERN :param email: email of the receiver :param selected_cluster: the name of cluster that we want to send the info of :param ca_cert: ca_cert of the cluster :param server_ip: ip of the cluster :return: """ self.log.info("Sending email!") try: from email.mime.text import MIMEText body = ''' Cluster name: {selected_cluster}\n\nCA Cert: {ca_cert}\n\nServer IP: {server_ip} ''' # Sending the mail body = body.format(selected_cluster=selected_cluster, ca_cert=ca_cert, server_ip=server_ip) msg = MIMEText(body) msg["From"] = os.environ["USER"] + "@cern.ch" msg["To"] = email msg["Subject"] = "Credentials for cluster: " + selected_cluster p = subprocess.Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=subprocess.PIPE) p.communicate(msg.as_bytes()) self.log.info("Successfully sent email") except Exception as e: # Handle email exceptions error = 'Cannot send email.' self.log.info(str(e)) self.send({'msgtype': 'added-user-unsuccessfully', 'error': error})
def request_doi(archive_no, title, yr, authors, ent): """Dispatch email to specified addresses using UNIX sendmail.""" from email.mime.text import MIMEText from subprocess import Popen, PIPE try: ent_email = get_ent_email(ent) base = get_config('base') default_emails = get_config('email') email_addr = ','.join([default_emails, ent_email]) body = f'URL: {base}/classic/app/archive/view?id={archive_no}\n' body += f'Creators: {authors}\n' body += f'Title: {title}\n' body += 'Publisher: Paleobiology Database\n' body += f'Publication Year: {yr}\n' body += 'Resource Type: Dataset\n' body += '========\n' body += f'PBDB Archive ID Number: {archive_no}\n' body += 'DOI: Pending\n' msg = MIMEText(body) msg['From'] = '*****@*****.**' msg['To'] = email_addr msg['Subject'] = 'PBDB archive DOI request' p = Popen(['/usr/sbin/sendmail', '-t', '-oi'], stdin=PIPE) return p.communicate(msg.as_bytes()) except exception as e: return e
def my_sendmail(fr: str, to: str, subj: str, body: str) -> tuple: msg = MIMEText(body, 'plain', 'utf-8') msg["From"] = fr msg["To"] = to msg["Subject"] = subj p = subprocess.Popen(["/usr/sbin/sendmail", "-t"], stdin=subprocess.PIPE) return p.communicate(msg.as_bytes())
def main(): """Shows basic usage of the Gmail API. Creates a Gmail API service object and outputs a list of label names of the user's Gmail account. """ credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1', http=http) # create a MIMEText object, that contains the body of the message m = MIMEText('this is a test') # add the to field of the message m['to'] = '*****@*****.**' # add the from field of the message m['from'] = '*****@*****.**' # add the subject field of the message m['subject'] = 'TEST' # Encode your MIMEText object as bytes and decode it as 'utf-8' raw = base64.urlsafe_b64encode(m.as_bytes()).decode('utf-8') # body of the message is a dictionary mapped to 'raw' is the MIMEText object that was decoded, and re-encoded body = {'raw': raw} # Create a messages object from your service object messages = service.users().messages() # create and send your message using your messages object, and .execute() message = messages.send(userId='me', body=body).execute()
def email(): """Send an email report with the current log file. This method sends the current log file to the email recipients as specified in the config module. It is not meant to be called independently from the command line. """ sender = CONFIG['GENERAL']['EMAIL_SENDER'] recipients = CONFIG['GENERAL']['EMAIL_REPORT_RECIPIENTS'] from email.mime.text import MIMEText with open(CONFIG['GENERAL']['LOG_FILE'], 'rb') as fp: log_content = fp.read() if not PY2: log_content = log_content.decode() message = MIMEText(log_content) message['Subject'] = CONFIG['GENERAL']['EMAIL_SUBJECT'] message['From'] = sender message['To'] = ','.join(recipients) p = subprocess.Popen( ['/usr/sbin/sendmail', '-t'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, ) if PY2: p.communicate(message.as_string()) else: p.communicate(message.as_bytes())
def create_message(sender, to, subject, message_text): message = MIMEText(message_text) message['to'] = to message['from'] = sender message['subject'] = subject encode_message = base64.urlsafe_b64encode(message.as_bytes()) return {'raw': encode_message.decode()}
def send_email(self, subject='', html='', text = None, send_to=(Config.MAIL_GMAIL, )): # if exception: # _, _, tb = sys.exc_info() # traceback.print_tb(tb) # tb_info = traceback.extract_tb(tb) # filename_, line_, func_, text_ = tb_info[-1] # message = 'An error occurred on File "{file}" line {line}\n {assert_message}'.format( # line=line_, assert_message=exception.args, file=filename_) # text = message # if template: # text = render_template(template + '.html', **kwargs) # msg = MIMEText(text, 'html') # else: # msg = MIMEText(text, 'plain') msg = MIMEText(html, 'html') msg['Subject'] = subject msg['From'] = self.username msg['To'] = ','.join(send_to) server = smtplib.SMTP(Config.MAIL_SERVER) server.starttls() server.login(self.username, self.password) server.sendmail(self.username, send_to, msg.as_bytes()) server.quit()
def CreateMessage(self, sender, to, subject, message_text): message = MIMEText(message_text, 'html') message['to'] = to message['from'] = sender message['subject'] = subject return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}
def send(self, subject, text): mcfg = self._config.get('mail') if not mcfg or not mcfg.get('send',False): print('Not configured to send mail.') return try: gm = self._gauth.get_service('gmail'); m = MIMEText(text) tolist = mcfg.get('to',[]) if isinstance(tolist, str): tolist = [ tolist ] m['to'] = ','.join(tolist) m['subject'] = subject b64_bytes = base64.urlsafe_b64encode(m.as_bytes()) b64_str = b64_bytes.decode() body = {'raw': b64_str} dr = gm.users().drafts().create(userId='me',body={'message': body}).execute() print('draft',dr) if dr and dr.get('id',None): res = gm.users().drafts().send(userId='me', body={'id':dr['id']}).execute() print('res',res) return res except Exception as e: print('An Error occured',e) return None
def send_message(): # Opens file with emails with open("contacts.csv") as file: reader = csv.reader(file) # Skip header row next(reader) # Loops through emails file for email in reader: # Email content gmail_content = 'Systemet har känt av ett tweet med hashtagen "#rödakorsethjälp", vänligen inspektera.' # Email subject gmail_subject = 'Systemvarning från Twitter!' # Revomes brackets and quotations email = "".join(email) print("\nSkickar till: " + email) # Uses email preferences message = MIMEText(gmail_content) message ['subject'] = gmail_subject message ['to'] = email # Gmail API reads messages raw = base64.urlsafe_b64encode(message.as_bytes()) raw = raw.decode() body = {'raw': raw} # Sends the message try: message = (service.users().messages().send(userId='me', body=body).execute()) print("Ett email har skickats!") # If any error happends except errors.MessageError as error: print('An error occurred: %s' % error)
def make_new_email(name, message): """ Create a message for an email. Args: name: Name of recipient message_text: The text of the email message. Returns: An object containing a base64url encoded email object. """ message_text = f"{name}, {message}" message = MIMEText(message_text) message['to'] = get_carrier_return_address(number_dictionary[name]) #this was an email address I used for a different project that I wasn't nervous about #giving extended send etc. credentials to message['from'] = '*****@*****.**' #the subject shows up in the text as being within parenthesis so "(Task reminder)" message['subject'] = """Task reminder\n""" b64_bytes = base64.urlsafe_b64encode(message.as_bytes()) b64_string = b64_bytes.decode() body = {'raw': b64_string} return body
def reply_message(self, message_id, message_text, user_id='me'): rep_msg = self.service.users().messages().get( id=message_id, userId=user_id).execute() payload_h = rep_msg['payload']['headers'] #Export sections of the list headers head_sect = {} for i in range(0, len(payload_h)): head_sect[payload_h[i]['name']] = i message = MIMEText(message_text) message['To'] = payload_h[head_sect['From']]['value'] message['From'] = self.service.users().getProfile( userId='me').execute()['emailAddress'] message['Subject'] = payload_h[head_sect['Subject']]['value'] message['In-Reply-To'] = payload_h[head_sect['Message-ID']]['value'] message['References'] = payload_h[head_sect['Message-ID']]['value'] head_sect.clear() message = { 'raw': base64.urlsafe_b64encode(message.as_bytes()).decode() } message['threadId'] = rep_msg['threadId'] try: msg = (self.service.users().messages().send( userId=user_id, body=message).execute()) print('Message Id: %s' % msg['id']) return msg except HttpError as error: print('An error occurred: %s' % error)
def create_message(to, subject, message_text): message = MIMEText(message_text) message['to'] = to message['from'] = formataddr(('KUN Lab採用 (かめすた)', '*****@*****.**')) message['subject'] = subject encode_message = base64.urlsafe_b64encode(message.as_bytes()) return {'raw': encode_message.decode()}
def create_message_simple(self, sender, to, subject, message_text): """Create a text-only message for an email. `Args:` sender: str Email address of the sender. to: str Email address(es) of the recipient(s). subject: str The subject of the email message. message_text: str The text of the email message. `Returns:` dict An object containing a base64url encoded email object. """ logger.info("Creating a simple message...") message = MIMEText(message_text) message['to'] = to message['from'] = sender message['subject'] = subject msg = {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()} logger.debug(msg) logger.info("Encoded simple message sucessfully created.") return msg
def sendMail(message_text, loan): print("inside send mail") creds = None tokenPath = os.path.join(APP_PATH, token_path) if os.path.exists(tokenPath): with open(os.path.join(APP_PATH, token_path), "rb") as token: creds = pickle.load(token) if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) with open('token.pickle', 'wb') as token: pickle.dump(creds, token) service = build('gmail', 'v1', credentials=creds) message = MIMEText(message_text) message['to'] = loan.borrower.email message['from'] = '*****@*****.**' message['subject'] = 'Loan Approval' raw = base64.urlsafe_b64encode(message.as_bytes()) raw = raw.decode() body = {'raw': raw} message = (service.users().messages().send(userId='me', body=body).execute()) print(message)
def create_message(SENDER, TO, SUBJECT, MESSAGE_P_TEXT): """Create a message for an email. Args: SENDER: Email address of the sender. This field won't be required since the logged user will be sending the email. TO: Email address of the receiver. SUBJECT: The subject of the email message. MESSAGE_P_TEXT: The text of the email message. Returns: An object containing a base64url encoded email object. [CHANGED] Author's modification: NOW RETURS A BASE64URL DECODED, OTHERWISE IT BROKES """ message = MIMEText(MESSAGE_P_TEXT, 'html') toField ='' for t in TO: toField += " " + str(t) + ";" message['from'] = '' #DO NOT NEEDED message['to'] = toField message['subject'] = SUBJECT raw = base64.urlsafe_b64encode(message.as_bytes()).decode() return {"raw": raw}
def createEmailMessage(self, subject, message_text): logger.debug("Creating message") message = MIMEText(message_text, "html") message["to"] = config.settings["email_receiver"] message["from"] = config.settings["email_sender"] message["subject"] = subject return {"raw": base64.urlsafe_b64encode(message.as_bytes()).decode()}
def create_msg(sender, to, subject, text): message = MIMEText(text) message["to"] = to message["from"] = sender message["subject"] = subject return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()} # encrypt and get in format to send
def send_email(to, subject, email_template, sender='*****@*****.**', **kwargs): """ Send an e-mail from the via-gmail Args: sender: Email address of the sender. to: Email address of the receiver. subject: The subject of the email message. content: The text of the email message. """ service = build_gmail_service() user_id = '*****@*****.**' msg = MIMEText(render_template(email_template, **kwargs), 'html') msg['to'] = to msg['from'] = sender msg['subject'] = subject body = {'raw': base64.urlsafe_b64encode(msg.as_bytes()).decode()} try: email = (service.users().messages().send(userId=user_id, body=body) .execute()) print('Sent e-mailmessage Id: %s' % email['id']) return email except errors.HttpError: flash('Er is iets mis gegaan met het versturen van de e-mail')
def notify(message, subject=description, level='info', sendmail=True): # log message getattr(log, level)('{}: {}'.format(config['email'], message)) # send mail if sendmail parameter is true and config notify settings defined if sendmail and config.get('notify'): # set email content email = MIMEText(message) email['Subject'] = subject email['To'] = config['notify'] if config.get('from'): email['From'] = config['from'] # send email via smtp server if config provided, otherwise via sendmail command if config.get('smtp'): # initialize smtp server object server = SMTP(config['smtp'].get('server', 'localhost')) # login smtp server if credentials provided if config['smtp'].get('username') and config['smtp'].get( 'password'): server.login(config['smtp']['username'], config['smtp']['password']) # send email server.sendmail(config.get('from', 'craigslist-renew@localhost'), config['notify'], email.as_string()) else: # initialize process object process = Popen(['/usr/sbin/sendmail', '-t'], stdin=PIPE) # send email process.communicate(email.as_bytes())
def create_message(self,sender, to, subject, message_text): message = MIMEText(message_text) message['to'] = to message['from'] = sender message['subject'] = subject # message['Reply-To'] = reply-to return {'raw': base64.urlsafe_b64encode(message.as_string())} return {'raw': base64.urlsafe_b64encode(message.as_bytes())}
def send_email(FromName=None, subject='', html='', text=None, send_to=[Config.MAIL_GMAIL]): msg = MIMEText(html, 'html') msg['Subject'] = subject msg['From'] = "%s <%s>" % (FromName, Config.MAIL_USERNAME) if FromName else Config.MAIL_USERNAME msg['To'] = ','.join(send_to) server = smtplib.SMTP(Config.MAIL_SERVER) server.starttls() server.login(Config.MAIL_USERNAME, Config.MAIL_PASSWORD) server.sendmail(Config.MAIL_USERNAME, send_to, msg.as_bytes()) server.quit()
def sendEmail(subject, body, targetEmailAddress, senderEmailAddress): #def create_message(sender, to, subject, message_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. Returns: An object containing a base64url encoded email object. """ message = MIMEText(body) message['to'] = targetEmailAddress message['from'] = senderEmailAddress message['subject'] = subject # Some bugs with python 3 and encoding the message properly. # https://stackoverflow.com/questions/38633781/python-gmail-api-not-json-serializable #encodedMessage = {'raw': base64.urlsafe_b64encode(message.as_string().encode("utf-8"))} rawMessage = base64.urlsafe_b64encode(message.as_bytes()) rawMessage = rawMessage.decode() encodedMessage = {'raw': rawMessage} #def send_message(service, user_id, message): """Send an email message. Args: service: Authorized Gmail API service instance. user_id: User's email address. The special value "me" can be used to indicate the authenticated user. (i don't understand how to use "me") message: Message to be sent. Returns: Sent Message. """ service = getGmailService() try: message = (service.users().messages().send(userId='me', body=encodedMessage).execute()) print('Message Id: %s' % message['id']) return message except HttpError as err: print('An error occurred: %s' % err) if err.resp.status in [403, 500, 503]: sleep(5) else: raise
def createMessage(sender, to, subject, message_text): message = MIMEText(message_text) message['to'] = to message['from'] = sender message['subject'] = subject raw = base64.urlsafe_b64encode(message.as_bytes()) raw = raw.decode() body = {'raw': raw} return body
def send_text_message(self, message_text): message = MIMEText(message_text) message['to'] = os.environ['PHONE_NUMBER_EMAIL'] message['from'] = os.environ['GMAIL_PI_EMAIL'] raw = base64.urlsafe_b64encode(message.as_bytes()) raw = raw.decode() body = {'raw': raw} try: message = (self.service.users() .messages().send(userId='me', body=body) .execute()) except errors.HttpError as error: print('An error occurred: %s' % error)
def send_mail(checker): if checker: SUBJECT = "Автоматический backup your site успешно выполнен" text= 'Бэкап сайта your site успешно выполнен и загружен на ЯндексДиск your site' else: SUBJECT = "Автоматический backup your site завершился с ошибкой" text= 'Во время выполения бэкапа произошла ошибка, необходимо проверить на сервере' TO = ['*****@*****.**', '*****@*****.**'] FROM = '*****@*****.**' msg = MIMEText(text, 'plain') msg['FROM'] = FROM msg['TO'] = ','.join(TO) msg['SUBJECT'] = SUBJECT p = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE) p.communicate(msg.as_bytes())
def create_message(to, subject, message_text, sender='*****@*****.**'): """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. Returns: An object containing a base64url encoded email object. """ message = MIMEText(message_text) message['to'] = to message['from'] = sender message['subject'] = subject return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode('utf8')}
def CreateMessage(sender, to, subject, message_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. Returns: An object containing a base64url encoded email object. """ message = MIMEText(message_text) message['To'] = to message['From'] = sender message['Subject'] = subject return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode('utf-8')}
def CreateMessage(sender, to, subject, message_text, service): """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. Returns: An object containing a base64 encoded email object. """ message = MIMEText(message_text) message['to'] = to message['from'] = sender message['subject'] = subject x = base64.b64encode(message.as_bytes()) x = x.decode() body = {'raw':x} return body
def CreateMessage(sender, to, subject, message_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. Returns: An object containing a base64 encoded email object. """ message = MIMEText(message_text) message['to'] = to message['from'] = sender message['subject'] = subject raw = None try: raw = {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()} except Exception: raw = {'raw': base64.urlsafe_b64encode(message.as_string())} return raw
# MIME message generation with 8-bits header -Chapter 9 # mime-headers.py # This program requires Python 2.2.2 or above from email.mime.text import MIMEText from email.header import Header from email import utils message = """Hello, This is a test message from chapter 9. I hope you enjoy it! -- Anonymous""" msg = MIMEText(message) msg["To"] = "*****@*****.**" fromhdr = Header("Michael M\xfcller", "utf-8") fromhdr.append("<*****@*****.**>", "ascii") msg["From"] = fromhdr msg["Subject"] = Header("Test Message, Chapter 10") msg["Date"] = utils.formatdate(localtime=1) msg["Message-ID"] = utils.make_msgid() fd = open("header.txt", mode="wb") fd.write(msg.as_bytes()) fd.close() print(msg.as_string())
#%% if nrow > 0: SCOPES = 'https://www.googleapis.com/auth/gmail.send' creds = None if os.path.exists('/path_to_token/token.pickle'): with open('/path_to_token/token.pickle', 'rb') as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( '/path_to_credentials/credentials.json', SCOPES) creds = flow.run_local_server() # Save the credentials for the next run with open('/path_to_token/token.pickle', 'wb') as token: pickle.dump(creds, token) service = build('gmail', 'v1', credentials=creds) message_text = 'www.recreation.gov/camping/campgrounds/232487/availability' message = MIMEText(message_text) message['to'] = '*****@*****.**' message['from'] = '*****@*****.**' message['subject'] = 'Campsite available' message = {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()} service.users().messages().send(userId='*****@*****.**', body=message).execute()
def send_email(address, subject, content): p = Popen(["/usr/sbin/sendmail", "-i", "--", address], stdin=PIPE) msg = MIMEText(content) msg['Subject'] = subject msg['To'] = address p.communicate(msg.as_bytes())
except: print('time out!'+'['+stock_code+'] not found!') sys.exit(1) #print(str(lower_num),str(higher_num)) #sys.exit(1) now = datetime.date.today() yestoday = now - datetime.timedelta(days=1) price = float(df.price[0]) #msg = MIMEText("Here is the body of my message") #msg["From"] = "*****@*****.**" #msg["To"] = "*****@*****.**" #msg["Subject"] = "This is the subject." #p = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE) #p.communicate(msg.as_string()) if price < lower_num or price > higher_num: mail_body = "股票代码: "+str(stock_code)+"当前价格: "+str(price) msg = MIMEText(mail_body) msg["From"] = str(mail_from) msg["To"] = str(mail_to) msg["Subject"] = "股票消息提醒" p = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE) #p.communicate(msg.as_string()) #python2 p.communicate(msg.as_bytes())
m = re_cc.search(line); if m and m.groups: cc.append(m.groups()[0]) # convert to set which removes dups too to = set(to) cc = set(cc) if args.debug: print("To: ", to) print("Cc: ", cc) msg = MIMEText(body.encode('utf-8'), 'plain', 'utf-8') msg["From"] = Header("{}".format(from_name), "utf-8") msg["From"].append(" <{}>".format(from_email), 'us-ascii') msg["Subject"] = Header('patch "{}" added to {}'.format(subject, tree_name), "utf-8") msg["To"] = Header(", ".join(to), "us-ascii") msg["Cc"] = Header(", ".join(cc), "us-ascii") if args.debug or args.verbose > 1: print(msg.as_bytes().decode(encoding='utf-8')) if not args.dry_run: p = subprocess.Popen(["msmtp", "-t", "-oi"], stdin=subprocess.PIPE) p.communicate(bytes(msg.as_bytes().decode(encoding="utf-8"), "utf-8")) print("Acknowledged: {} \"{}\"".format(str(commit.oid)[:SHA_LEN], subject)) if not commit: print("Empty commit range. Exiting") sys.exit(0)