def sendEmail(args, returnCode): """ Try to send an email to the user. Errors must be non-fatal. """ try: import smtplib from email.message import EmailMessage msg = EmailMessage() msg['Subject'] = "Snakepipes completed" msg['From'] = args.emailSender msg['To'] = args.emailAddress if returnCode == 0: msg.set_content("The pipeline finished successfully\n") else: msg.set_content("The pipeline failed with exit code {}\n".format(returnCode)) if args.onlySSL: s = smtplib.SMTP_SSL(args.smtpServer, port=args.smtpPort) else: s = smtplib.SMTP(args.smtpServer, port=args.smtpPort) if args.smtpUsername: s.login(args.smtpUsername, args.smtpPassword) s.send_message(msg) s.quit() except: sys.stderr.write("An error occured while sending the email.\n") pass
def test_send_message_uses_smtputf8_if_addrs_non_ascii(self): msg = EmailMessage() msg['From'] = "Páolo <fő[email protected]>" msg['To'] = 'Dinsdale' msg['Subject'] = 'Nudge nudge, wink, wink \u1F609' # XXX I don't know why I need two \n's here, but this is an existing # bug (if it is one) and not a problem with the new functionality. msg.set_content("oh là là, know what I mean, know what I mean?\n\n") # XXX smtpd converts received /r/n to /n, so we can't easily test that # we are successfully sending /r/n :(. expected = textwrap.dedent("""\ From: Páolo <fő[email protected]> To: Dinsdale Subject: Nudge nudge, wink, wink \u1F609 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 8bit MIME-Version: 1.0 oh là là, know what I mean, know what I mean? """) smtp = smtplib.SMTP( HOST, self.port, local_hostname='localhost', timeout=3) self.addCleanup(smtp.close) self.assertEqual(smtp.send_message(msg), {}) self.assertEqual(self.serv.last_mailfrom, 'fő[email protected]') self.assertEqual(self.serv.last_rcpttos, ['Dinsdale']) self.assertEqual(self.serv.last_message.decode(), expected) self.assertIn('BODY=8BITMIME', self.serv.last_mail_options) self.assertIn('SMTPUTF8', self.serv.last_mail_options) self.assertEqual(self.serv.last_rcpt_options, [])
def do_genmime(args): """Execute the ``genmime`` subcommand. Unlike ``genhtml``, this command inlines images (which ``genhtml`` can't do becaus ``cid`` embedding is not, AFAIK, usable outside of email clients, but ``genhtml`` is most useful for previewing emails in browsers!).""" # Set up the email md_source = args.source.read() mail = EmailMessage() mail["From"] = Address(args.sender_name, args.sender_email) issue_no, _, _ = load_issue(md_source) mail["Subject"] = "Frontiers Fortnightly #{}".format(issue_no) # First, produce the text part text_content = render_mail_template(md_source, TEXT_TEMPLATE_NAME, args.sender_name, args.sender_email) mail.set_content(text_content) # Next, produce the HTML part minified_html = generate_html(md_source, HTML_TEMPLATE_NAME, args.sender_name, args.sender_email) inlined_html = inline_images(minified_html) mail.add_alternative(inlined_html, subtype="html") if "b" in args.dest.mode: args.dest.write(bytes(mail)) else: args.dest.write(str(mail))
def flush(self): self.acquire() try: if len(self.buffer) > 0: import smtplib from email.message import EmailMessage import email.utils port = self.mailport if not port: port = smtplib.SMTP_PORT smtp = smtplib.SMTP( self.mailhost, port, timeout=self.smtp_timeout) msg = EmailMessage() msg['From'] = self.fromaddr msg['To'] = ','.join(self.toaddrs) msg['Subject'] = self.getSubject(self.buffer) msg['Date'] = email.utils.localtime() msg.set_content('\n'.join(self.format(r) for r in self.buffer)) if self.username: if self.secure is not None: smtp.ehlo() smtp.starttls(*self.secure) smtp.ehlo() smtp.login(self.username, self.password) smtp.send_message(msg) smtp.quit() self.buffer = [] except Exception: self.handleError(self.buffer[-1]) finally: self.release()
def send_email(self, recipient_email, subject, body): """Sends an email to a defined address. """ # prepare message msg = EmailMessage() msg['Subject'] = subject msg['From'] = Address(self.sender_email) #self.sender_name, addr_spec= msg['To'] = Address(self.sender_name, recipient_email) msg.set_content(body) ''' message = MIMEText(body) message["Subject"] = subject message["From"] = self.mail message["To"] = recipient_email msg = message.as_string() ''' server = smtplib.SMTP(self.server) if self.use_tls: # deliberately starts tls if using TLS server.ehlo() server.starttls() server.ehlo() server.login(self.login, self.password) server.send_message(msg) server.quit() return
def _send(self, msg_content): # reference # - https://docs.python.org/3/library/email-examples.html send_msg = EmailMessage() send_msg['From'] = self.email_from # multiple mail_to # ex) [email protected],[email protected] send_msg['To'] = self.email_to if len(self.email_cc) > 0: send_msg['CC'] = self.email_cc send_msg['Subject'] = self.subject send_msg.set_content(msg_content) s = smtplib.SMTP(self.smtp_server, self.smtp_port) # Hostname to send for this command defaults # to the fully qualified domain name of the local host. s.ehlo() # Puts connection to SMTP server in TLS mode s.starttls() s.ehlo() s.login(self.smtp_account, self.smtp_password) s.set_debuglevel(1) s.send_message(send_msg) s.quit()
def make_message_object(origin, destination, subject, content): m = EmailMessage() m.set_content(content) m['Subject'] = subject m['From'] = origin m['To'] = destination return m
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 create_msg(recv: str, subject: str, body: str, sender: str=SENDER_EMAIL) -> EmailMessage: msg = EmailMessage() msg['To'] = recv msg['From'] = sender msg['Subject'] = subject msg.set_content(body) return msg
def sample_message(): msg = EmailMessage() msg['From'] = '*****@*****.**' msg['To'] = 'Test Recipient <*****@*****.**>, [email protected]' msg['Cc'] = 'Test CC <*****@*****.**>, [email protected]' msg['Bcc'] = 'Test BCC <*****@*****.**>, [email protected]' msg.set_content('Test content') return msg
def send_email(email, subject, message): msg = EmailMessage() msg['Subject'] = subject msg['From'] = '*****@*****.**' msg['To'] = email msg.set_content(message) with smtplib.SMTP('localhost') as s: s.send_message(msg)
def post(self): msg = EmailMessage() msg['Subject'] = self.get_argument('subject') msg['To'] = self.get_argument('email') msg['From'] = FROM_ADDR msg.set_content(self.get_argument('message')) smtp = yield self.application.get_smtp_client() smtp.send_message(msg) self.render('index.html')
def __create_message(subject, message_body, from_email, to_emails): ''' Take the subject, message body, from email, and to emails list and create a message object to send off. ''' msg = EmailMessage() msg.set_content(message_body) msg['Subject'] = subject msg['From'] = from_email msg['To'] = __get_list(to_emails) return msg
def create_preference_message() -> PreferenceEmail: """Creates new email with a swa preferences from a template :return: PreferenceEmail """ msg = EmailMessage() msg['X-Oddpost-Class'] = 'prefs' msg['Subject'] = '[prefs(v2.1) data]' msg['From'] = '*****@*****.**' msg.set_charset('utf-8') msg.set_content(PREFERENCE_TEMPLATE) return PreferenceEmail(0, msg)
def test_headeremail2list_1(self): msg = EmailMessage() msg['Subject'] = 'Test subject éèàöüä${}' msg['From'] = Address("John Doe", "john.doe", "example.com") msg['To'] = (Address("Jané Doe", "jane.doe", "example.com"), Address("James Doe", "james.doe", "example.com")) msg.set_content('''Hi, Lorem ipsüm dolor sit amét, consectetur 10$ + 5€ adipiscing elit. Praesent feugiat vitae tellus et molestie. Duis est ipsum, tristique eu pulvinar vel, aliquet a nibh. Vestibulum ultricies semper euismod. Maecenas non sagittis elit. Mauris non feugiat leo. Cras vitae quam est. Donec dapibus justo ut dictum viverra. Aliquam eleifend tortor mollis, vulputate ante sit amet, sodales elit. Fusce scelerisque congue risus mollis pellentesque. Sed malesuada erat sit amet nisl laoreet mollis. Suspendisse potenti. Fusce cursus, tortor sit amet euismod molestie, sem enim semper quam, eu ultricies leo est vel turpis. ''') assert sorted(eml_parser.eml_parser.headeremail2list(mail=msg, header='to')) == ['*****@*****.**', '*****@*****.**']
def _prepare_message(self): msgs = [] for rec_group in self.recipients: msg = EmailMessage() msg['From'] = self.frm msg['To'] = rec_group content = self.content msg['Subject'] = content['meta']['subject'][0] msg.set_content(content['raw']) msg.add_alternative(content['html'], subtype='html') msgs.append(msg) return msgs
def send_email(email_address, email_password, error = 'None'): server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login(email_address, email_password) msg = EmailMessage() msg['Subject'] = 'Father, I failed you' msg['From'] = email_address msg['To'] = "*****@*****.**" msg.set_content(error) server.send_message(msg) server.quit() print('Email sent')
def _create_confirmation_message(self, details, url): config = self.settings['smtp_config'] msg = EmailMessage() msg['Subject'] = 'ChessRank: Please confirm your email address' msg['To'] = details['email'] msg['From'] = config['from'] loader = tornado.template.Loader(self.settings['template_path']) body = loader.load('verify.html').generate(name=details['name'], url=url).decode('utf-8') msg.set_content(body, subtype='html') return msg
def create_mail(sender, recipient, subject, body, attachments, gpgme_ctx): """Create an email either as single or multi-part with attachments. """ msg = EmailMessage(policy=mailgen_policy) msg.set_content(body) attachment_parent = msg if gpgme_ctx is not None: msg.make_mixed() attachment_parent = next(msg.iter_parts()) if attachments: for args, kw in attachments: attachment_parent.add_attachment(*args, **kw) if gpgme_ctx is not None: signed_bytes = attachment_parent.as_bytes() hash_algo, signature = detached_signature(gpgme_ctx, signed_bytes) msg.add_attachment(signature, "application", "pgp-signature", cte="8bit") # the signature part should now be the last of two parts in the # message, the first one being the signed part. signature_part = list(msg.iter_parts())[1] if "Content-Disposition" in signature_part: del signature_part["Content-Disposition"] msg.replace_header("Content-Type", "multipart/signed") micalg = hash_algorithms.get(hash_algo) if micalg is None: raise RuntimeError("Unexpected hash algorithm %r from gpgme" % (signature[0].hash_algo,)) msg.set_param("protocol", "application/pgp-signature") msg.set_param("micalg", micalg) msg.add_header("From", sender) msg.add_header("To", recipient) msg.add_header("Subject", subject) msg.add_header("Date", formatdate(timeval=None, localtime=True)) # take the domain part of sender as the domain part of the message # ID. We assume that sender has the form local@domain, so we can # just the part of sender after the '@'. sender_domain = sender.partition("@")[-1] if not sender_domain: raise RuntimeError("Could not extract the domain from the sender (%r)" " for the Message-ID" % (sender,)) msg.add_header("Message-Id", make_msgid(domain=sender_domain)) return msg
def send_email( email_from: str, email_to: str, location: Location, screenshot: MapScreenshot, template: str = None, ) -> None: """ Send the traffic info email. Args: email_from: Email sender's address. email_to: Email recipient's address. location: The map's location. screenshot: The map's screenshot. template: The path to the email's Jinja2 template, templates/email.j2 if not specified. """ if template is None: template = os.path.join(DIR, "templates", "email.j2") logger = logging.getLogger(__name__) map_cid = make_msgid() context: Context = { "url": f"https://www.google.fr/maps/@{location.latitude}," f"{location.longitude},{location.zoom}z/data=!5m1!1e1", "width": screenshot.width, "height": screenshot.height, "map_cid": map_cid[1:-1], } content = f""" Today's traffic conditions. {context["url"]} Have a safe trip back home! """ html = render_template(template, context) email = EmailMessage() email["Subject"] = "Traffic info" email["From"] = Address("Traffic info", addr_spec=email_from) email["To"] = email_to email.set_content(content) email.add_alternative(html, subtype="html") with open(screenshot.path, "rb") as img: email.get_payload()[1].add_related(img.read(), "image", "png", cid=map_cid) try: with smtplib.SMTP("localhost") as smtp: smtp.send_message(email) except ConnectionRefusedError as exception: logger.error("Unable to send email(%s)", exception)
def mkattachment(blob, mime_type, disposition, filename): assert isinstance(blob, bytes) mime_type, params = parse_header(mime_type) maintype, _, subtype = mime_type.partition('/') attach = EmailMessage() attach.set_content( blob, maintype, subtype, disposition=disposition, filename=filename, params=params, ) return attach
def SendEmail( to, subject, template, **kwargs ): app = current_app._get_current_object() msg = EmailMessage() msg["Subject"] = subject msg["From"] = os.environ.get( "MAIL_USERNAME" ) msg["To"] = to msg.set_content(render_template( template + ".txt", **kwargs ) ) server = smtplib.SMTP( app.config["MAIL_SERVER"], app.config["MAIL_PORT"] ) server.starttls() server.ehlo() server.login( os.environ.get( "MAIL_USERNAME" ), os.environ.get( "MAIL_PASSWORD" ) ) server.send_message( msg, os.environ.get( "MAIL_USERNAME", [to] ) ) server.quit()
def send_email(self, subject: str, content: str, receiver: str = ""): """""" # Start email engine when sending first email. if not self.active: self.start() # Use default receiver if not specified. if not receiver: receiver = SETTINGS["email.receiver"] msg = EmailMessage() msg["From"] = SETTINGS["email.sender"] msg["To"] = SETTINGS["email.receiver"] msg["Subject"] = subject msg.set_content(content) self.queue.put(msg)
def contact(): def error(message): response = jsonify(message=message) response.status_code = 400 return response name = request.form.get('name', None) email_addr = request.form.get('email', None) phone = request.form.get('phone', '없음') message = request.form.get('message', None) if name is None: return error('이름을 적어주세요') if email_addr is None: return error('메일주소를 적어주세요') if message is None: return error('본문을 적어주세요') context = render_template( 'response.html', name=name, email_addr=email_addr, phone=phone, message=message ) msg = EmailMessage() msg['Subject'] = "고객님의 신규 상담이 접수되었습니다." msg['From'] = Address('Snoin', '*****@*****.**') msg['To'] = app.config['MAIL_LISTENERS'] + [Address(name, email_addr)] msg.set_content('접수되었습니다.') msg.add_alternative(context, subtype='html') try: with smtplib.SMTP_SSL('smtp.gmail.com', 465) as s: s.ehlo() s.login(app.config['SMTP_ID'], app.config['SMTP_PASSWORD']) s.send_message(msg) except smtplib.SMTPException as e: return error(str(e)) return jsonify(message='접수되었습니다.')
def test_parse_email_1(self): """Parses a generated sample e-mail and tests it against a known good result""" msg = EmailMessage() msg['Subject'] = 'Test subject éèàöüä${}' msg['From'] = Address("John Doe", "john.doe", "example.com") msg['To'] = (Address("Jané Doe", "jane.doe", "example.com"), Address("James Doe", "james.doe", "example.com")) msg.set_content('''Hi, Lorem ipsüm dolor sit amét, consectetur 10$ + 5€ adipiscing elit. Praesent feugiat vitae tellus et molestie. Duis est ipsum, tristique eu pulvinar vel, aliquet a nibh. Vestibulum ultricies semper euismod. Maecenas non sagittis elit. Mauris non feugiat leo. Cras vitae quam est. Donec dapibus justo ut dictum viverra. Aliquam eleifend tortor mollis, vulputate ante sit amet, sodales elit. Fusce scelerisque congue risus mollis pellentesque. Sed malesuada erat sit amet nisl laoreet mollis. Suspendisse potenti. Fusce cursus, tortor sit amet euismod molestie, sem enim semper quam, eu ultricies leo est vel turpis. ''') good_output_json = r'''{"header": {"header": {"content-transfer-encoding": ["quoted-printable"], "content-type": ["text/plain; charset=\"utf-8\""], "from": ["John Doe <*****@*****.**>"], "subject": ["Test subject \u00e9\u00e8\u00e0\u00f6\u00fc\u00e4${}"], "to": ["Jan\u00e9 Doe <*****@*****.**>, James Doe <*****@*****.**>"], "mime-version": ["1.0"]}, "from": "*****@*****.**", "subject": "Test subject \u00e9\u00e8\u00e0\u00f6\u00fc\u00e4${}", "received": [], "date": "1970-01-01T00:00:00+00:00", "to": ["*****@*****.**", "*****@*****.**"]}, "body": [{"content_header": {"content-transfer-encoding": ["quoted-printable"], "content-type": ["text/plain; charset=\"utf-8\""]}, "hash": "f765993eba20df87927f5bf6e947696d48bdf936e75508b9d126bbe8aa1a1497", "content_type": "text/plain"}]}''' good_output = json.loads(good_output_json) test_output_json = json.dumps(eml_parser.eml_parser.parse_email(msg), default=json_serial) test_output = json.loads(test_output_json) recursive_compare(good_output, test_output)
def _send_email(self, to, msg): match = re.fullmatch(r'Subject: ([^\n]+)\n\n(.+)', msg, re.DOTALL) if not match: raise ValueError('msg_invalid') msg = EmailMessage() msg['To'] = to msg['From'] = self.app.email msg['Subject'] = match.group(1) msg.set_content(match.group(2)) components = urlparse(self.app.smtp_url) host = components.hostname or 'localhost' port = components.port or 25 try: with SMTP(host=host, port=port) as smtp: smtp.send_message(msg) except OSError: raise EmailError()
def emit(self, record: LogRecord) -> None: """ Emit a record. Format the record and send it to the specified addresses. :param record: The record to send. :raise KeyboardInterrupt: If a keyboard interrupt occurs during mail transmission, it will be reraised. :raise SystemExit: If a ``sys.exit()`` interrupts the mail transmission, it will be reraised. """ # noinspection PyBroadException try: port = self.mailport if not port: port = SMTP_SSL_PORT if self.ssl else SMTP_PORT if self.ssl: smtp = SMTP_SSL(self.mailhost, port, timeout=self.timeout) else: smtp = SMTP(self.mailhost, port, timeout=self.timeout) msg = EmailMessage() msg['From'] = self.fromaddr msg['To'] = ','.join(self.toaddrs) msg['Subject'] = self.getSubject(record) msg['Date'] = email.utils.localtime() msg.set_content(self.format(record)) if self.username: if self.secure is not None: smtp.ehlo() smtp.starttls(*self.secure) smtp.ehlo() smtp.login(self.username, self.password) smtp.send_message(msg) smtp.quit() except (KeyboardInterrupt, SystemExit): raise except Exception: self.handleError(record)
def test_smtputf8_policy(self): msg = EmailMessage() msg['From'] = "Páolo <fő[email protected]>" msg['To'] = 'Dinsdale' msg['Subject'] = 'Nudge nudge, wink, wink \u1F609' msg.set_content("oh là là, know what I mean, know what I mean?") expected = textwrap.dedent("""\ From: Páolo <fő[email protected]> To: Dinsdale Subject: Nudge nudge, wink, wink \u1F609 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 8bit MIME-Version: 1.0 oh là là, know what I mean, know what I mean? """).encode('utf-8').replace(b'\n', b'\r\n') s = io.BytesIO() g = BytesGenerator(s, policy=policy.SMTPUTF8) g.flatten(msg) self.assertEqual(s.getvalue(), expected)
def send(recipient): """ Send demo credentials to recipient """ # Create the base text message. msg = EmailMessage() msg['Subject'] = "Connexion démo LabResult " msg['From'] = Address("", "*****@*****.**") msg['To'] = (Address("", recipient),) msg.set_content(mail_tmplt_txt.content) logo_cid = str(uuid.uuid4()) msg.add_alternative(mail_tmplt_html.content.format(logo_cid=logo_cid), 'html', 'utf-8') # Now add the related image to the html part. logo = os.path.join(os.path.dirname(__file__), "data", "logo.png") with open(logo, 'rb') as img: msg_image = MIMEImage(img.read(), name=os.path.basename(logo), _subtype="image/png" ) msg.attach(msg_image) msg_image.add_header('Content-ID', '<{}>'.format(logo_cid)) msg2 = MIMEText("Envoi des identifians de démo à %s" % recipient) msg2['Subject'] = "Connexion démo LabResult " msg2['From'] = "*****@*****.**" msg2['To'] = "*****@*****.**" # Send the message via local SMTP server. ret = False try : smtp_server = get_option('smtp_server', 'mail.gandi.net') with smtplib.SMTP_SSL(smtp_server) as s: USERNAME = get_option('smtp_login', '*****@*****.**') PASSWORD = get_option('smtp_password','pacman9732') s.login(USERNAME, PASSWORD) s.send_message(msg) s.send_message(msg2) ret = True except Exception : labresult.app.logger.error(traceback.format_exc()) finally: return ret
def sendmail(receiver_email, subject, content): login = conf.emailing.get('login', None) if login is not None: encoded_password = conf.emailing.get('encoded_password', None) if encoded_password is not None: password = decode_password(encoded_password) else: # legacy clear-text password password = conf.emailing.password msg = EmailMessage() msg.set_content(content) msg['Subject'] = '[sakura] ' + subject msg['From'] = conf.emailing.source msg['To'] = receiver_email if conf.emailing.ssl: cls = smtplib.SMTP_SSL else: cls = smtplib.SMTP s = cls(conf.emailing.host, conf.emailing.port) if login is not None: s.login(login, password) s.send_message(msg) s.quit()
import smtplib from email.message import EmailMessage from string import Template from pathlib import Path html = Template(Path("index.html").read_text()) email = EmailMessage() email["from"] = "Scott Bagley" email["to"] = "*****@*****.**" email["subject"] = "I love whooo??!" email.set_content(html.substitute({"name": "TinTin"}), "html") with smtplib.SMTP(host="smtp.gmail.com", port=587) as smtp: smtp.ehlo() smtp.starttls() smtp.login("*****@*****.**", "Dugan12345") smtp.send_message(email) print("Werkd")
class EmailActivity: def __init__(self): self.__message= EmailMessage() #To Add attachment(Ex: pdf, image, csv ...) to the email def addAttachment(self, filePath, fileName): with open(filePath, 'rb') as f: try: file_data = f.read() ctype, encoding = mimetypes.guess_type(f.name) if ctype is None or encoding is not None: ctype = "application/octet-stream" maintype, subtype = ctype.split("/", 1) print(maintype) print(subtype) except Exception as e: print(e) self.__message.add_attachment(file_data, maintype=maintype, subtype=subtype, filename=fileName) #Set up email server and secure connection def sendMail(self, userEmail, password, mailServer, port): with smtplib.SMTP(mailServer, port) as smtp: # setting up source mail server try: # initial set up connection print(mailServer) smtp.ehlo() # identifies the mail server we are using smtp.starttls() # To encrypt the connection smtp.ehlo() # To re-identify as encrypted connection smtp.login(userEmail, password) print("connection set up successful") print(smtp == None) smtp.send_message(self.__message) print("Message Sent Successfully!") print("LOG: Message sent on " + datetime.now().strftime("%d/%m/%Y %H:%M:%S")) # log message send time # < !Need to implement: save send log information to database> except Exception as e: print(e) # To add html content def addHtmlToMessage(self,html): try: self.__message.add_alternative(html, subtype='html') except Exception as e: print(e) def message(self,From, To ,Subject=None,textContent=None ): # To, From take string self.__message['Subject']= str(Subject) self.__message['From']= str(From) self.__message['To']= str(To) self.__message.set_content(textContent) def setContext(self,textContent): self.__message.set_content(textContent) def appendTextContext(self): """appaned textContext""" def getMessageObject(self): return self.__message
async def send_email(subject, content, to, username, password, display_name=None, cc_recipients=None, bcc_recipients=None, important=False, attach_img=None, content_type='text/plain', server='smtp.gmail.com', port=465): if not to or not username or not password or not subject or not content: return False def email_name(addr): return addr.split('@')[0] def email_domain(addr): return addr.split('@')[1] def generate_header(addresses): if isinstance(addresses, Address): return str(addresses) return ', '.join([str(addr) for addr in addresses]) display_name = display_name or email_name(username) from_addr = Address(display_name, display_name.lower(), email_domain(username)) to_addr = [ Address(email_name(recipient), email_name(recipient).lower(), email_domain(recipient)) for recipient in (to if isinstance(to, list) else [to]) ] cc_addr = [ Address(email_name(recipient), email_name(recipient).lower(), email_domain(recipient)) for recipient in (cc_recipients or []) ] bcc_addr = [ Address(email_name(recipient), email_name(recipient).lower(), email_domain(recipient)) for recipient in (bcc_recipients or []) ] # Build the list of recipients (To + Bcc): recipients = [addr.addr_spec for addr in (to_addr + cc_addr + bcc_addr)] # Build the EmailMessage object: message = EmailMessage() message.add_header("From", generate_header(from_addr)) message.add_header("To", generate_header(to_addr)) if cc_addr: message.add_header("Cc", generate_header(cc_addr)) if bcc_addr: message.add_header("Bcc", generate_header(bcc_addr)) message.add_header("Subject", subject) message.add_header("Content-type", content_type, charset="utf-8") if attach_img: message.add_attachment(attach_img, main_type='image', subtype=imghdr.what(None, attach_img)) if important: message.add_header("X-Priority", "1 (Highest)") message.add_header("X-Priority", "1 (Highest)") message.add_header("X-MSMail-Priority", "High") message.add_header("Importance", "High") message.set_content(content) async with SMTP(hostname=server, port=port, use_tls=True, username=username, password=password) as client: await client.sendmail(from_addr.addr_spec, recipients, message.as_string()) return True
import smtplib from email.message import EmailMessage msg = EmailMessage() msg['Subject'] = 'Automated Hiring Email Scammers' msg['From'] = 'Automation Hiring Scammers' msg['To'] = '[email protected],[email protected]' with open('EmailTemplate') as myfile: data = myfile.read() msg.set_content(data) for x in range(100): with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server: server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.login("*****@*****.**", "fathisgdgsdgsdgh@32423432") server.send_message(msg) print("Email has been sent")
from email.message import EmailMessage numberOfMistakes = 0 MAXIMUM_NUMBER_OF_MISTAKES = 5 # Change # Cron creates its OWN shell with the use specified through which it will run # (Still figuring out how to access the shell created by cron). EMAIL_ADDRESS = os.environ.get("EMAIL_USER") EMAIL_PASSWORD = os.environ.get("EMAIL_PASSWORD") MISTAKES_FILE_PATH = os.path.environ("MISTAKES_FILE_PATH") msg = EmailMessage() msg["Subject"] = "Your mom!" msg["From"] = EMAIL_ADDRESS msg["To"] = ["Put the list of recipient emails here"] msg.set_content("You suck!") # Fallback. msg.add_alternative(""" <!DOCTYPE html> <html> <body style='background-color: black;'> <h1 style='color: red;'>There is no way you have not strangled at least one stripper!</h1> </body> </html> """, subtype="html") # Opening file with the number of mistakes try: with open(os.path.environ("MISTAKES_FILE_PATH"), "r") as f: numberOfMistakes = int(f.read()) except FileNotFoundError: pass # No mistakes yet (but the cron keep checking every five minutes).
# eval() use to convert string to dictionary object data1=eval(t) if data1["from"] is None or data1["password"] is None: # Use Default Parameter here EMAIL_ADD = "" EMAIL_PASS = "" if len(data1["smtp_host"]) < 2: smtp_hos = 'smtp.gmail.com' if data1["port"] is None: port = 465 msg = EmailMessage() msg['Subject'] = data1["subject"] msg['From'] = EMAIL_ADD msg['To'] = data1["to"] msg['Cc'] = data1["cc"] msg.set_content(data1['body']+"\n Attachments :") # To WORK with MULTIPLE ATTCHMENTS FILE # OUR JSON contain path to multiple files which store inside a list list_of_attachments = list(data1['mailJson']['attachment'].split(',')) # attchment = is a string contain path to files, seprated by comma for attachment in list_of_attachments: with open(attachment, 'rb') as f: file_data = f.read() file_type = imghdr.what(f.name) file_name = f.name msg.add_attachment(file_data, maintype='image', subtype=file_type, filename=file_name) # multiple file attached # For PDF purpose # from pdf_mail import sendpdf # sendpdf(sender_email_add,recer_email_add, sender_email_pass, subj_of_email, body_of_email, filename, location_of_file)
class EmailGmail: def __init__(self, type_, files=None): self.cfg = ConfigParser().read('config.ini') self.type_ = type_ self.files = files self.init_vars(self.cfg) def init_vars(self, cfg): self.DISPLAY = cfg['GMAIL'].get('DISPLAY', None) self.LOCAL = cfg['GMAIL'].get('LOCAL', None) self.DOMAIN = cfg['GMAIL'].get('DOMAIN', None) self.SERVER = cfg['GMAIL'].get('SERVER', None) self.PORT_TLS = cfg['GMAIL'].get('PORT_TLS', None) self.PORT_SSL = cfg['GMAIL'].get('PORT_SSL', None) self.SENDER = Address(display_name=self.DISPLAY, username=self.LOCAL, domain=self.DOMAIN, addr_spec=f'{self.LOCAL}@{self.DOMAIN}') self.RECIPIENTS = [ Address(display_name='Ann Z', username='******', domain=self.DOMAIN, addr_spec=f'localpart@{self.DOMAIN}'), Address(display_name='Game Room', username='******', domain=self.DOMAIN, addr_spec=f'GameRoom@{self.DOMAIN}') ] self.STUDENTS = [ '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**' ] self.SUBJECT = f"{cfg['DEFAULT'].get('SUBJECT', '')} - {datetime.datetime.now()}" self.BODY_IMG = cfg['DEFAULT'].get('BODY_IMG', '') self.BODY_STUDENT = cfg['DEFAULT'].get('BODY_STUDENT', '') self.files = ['zip_file_01.zip', 'zip_file_02.zip'] def email_init(self): # MESSAGE HEADER self.message = EmailMessage() self.message['Subject'] = self.SUBJECT self.message['From'] = self.SENDER if self.type_ == 'attachment': self.message['To'] = ", ".join(self.RECIPIENTS) else: self.message['Bcc'] = ", ".join(self.STUDENTS) # MESSAGE BODY - PLAIN TEXT self.message.set_content(self.BODY_IMG if self.type_ == 'attachment' else self.BODY_STUDENT) # MESSAGE BODY - HTML ALTERNATIVE self.message.add_alternative(f"""\ <!DOCTYPE html> <html> <body> <h3 style="color:Crimson;">...HEADING...</h3> <p style="color:SlateGray;">{self.BODY_IMG if self.type_ == 'attachment' else self.BODY_STUDENT}</p> </body> </html> """, subtype='html') if self.type_ == 'attachment': # ATTACHMENTS for file in self.files: with open(file, 'rb') as f: self.f_data = f.read() self.f_name = f.name self.message.add_attachment( data=self.f_data, maintype='application', subtype='zip', # subtype='octet-stream', filename=self.f_name) def email_send(self): with smtplib.SMTP_SSL(host=self.SERVER, port=self.PORT_SSL) as self.smtp: # LOGIN self.smtp.login(user=self.cfg['GMAIL'].get('USER', None), password=self.cfg['GMAIL'].get('PASS', None)) # SEND EMAIL self.smtp.send_message(self.message)
# [GMAIL ACCOUNT EMAIL ADDRESS] # [GMAIL ACCOUNT PASSWORD] with open("credentials.file", "r") as file: credentials = file.read().split("\n") GMAIL_ADDRESS = credentials[0] GMAIL_PASSWD = credentials[1] # Datetime: https://stackoverflow.com/a/48283832/3339274 msg = EmailMessage() msg["Subject"] = ("[CI " + ("FAIL" if tests_contain_fail else "PASS") + "] SimVascular Python API Unit Test Report (" + ctime() + ")") msg["From"] = GMAIL_ADDRESS msg["To"] = recipients # Add plain-text version. msg.set_content(plain_text_msg) # Add HTML version of message. msg.add_alternative("""\ <!DOCTYPE html> <html> <body> """ + "".join(formatted_output) + "<br> <h1>List of Failed Tests:</h1>" + "".join(failed_tests) + """ </body> </html> """, subtype="html")
def build_email(self, email_from, email_to, subject, body, email_cc=None, email_bcc=None, reply_to=False, attachments=None, message_id=None, references=None, object_id=False, subtype='plain', headers=None, body_alternative=None, subtype_alternative='plain'): """Constructs an RFC2822 email.message.Message object based on the keyword arguments passed, and returns it. :param string email_from: sender email address :param list email_to: list of recipient addresses (to be joined with commas) :param string subject: email subject (no pre-encoding/quoting necessary) :param string body: email body, of the type ``subtype`` (by default, plaintext). If html subtype is used, the message will be automatically converted to plaintext and wrapped in multipart/alternative, unless an explicit ``body_alternative`` version is passed. :param string body_alternative: optional alternative body, of the type specified in ``subtype_alternative`` :param string reply_to: optional value of Reply-To header :param string object_id: optional tracking identifier, to be included in the message-id for recognizing replies. Suggested format for object-id is "res_id-model", e.g. "12345-crm.lead". :param string subtype: optional mime subtype for the text body (usually 'plain' or 'html'), must match the format of the ``body`` parameter. Default is 'plain', making the content part of the mail "text/plain". :param string subtype_alternative: optional mime subtype of ``body_alternative`` (usually 'plain' or 'html'). Default is 'plain'. :param list attachments: list of (filename, filecontents) pairs, where filecontents is a string containing the bytes of the attachment :param list email_cc: optional list of string values for CC header (to be joined with commas) :param list email_bcc: optional list of string values for BCC header (to be joined with commas) :param dict headers: optional map of headers to set on the outgoing mail (may override the other headers, including Subject, Reply-To, Message-Id, etc.) :rtype: email.message.EmailMessage :return: the new RFC2822 email message """ email_from = email_from or self._get_default_from_address() assert email_from, "You must either provide a sender address explicitly or configure "\ "using the combination of `mail.catchall.domain` and `mail.default.from` "\ "ICPs, in the server configuration file or with the "\ "--email-from startup parameter." headers = headers or {} # need valid dict later email_cc = email_cc or [] email_bcc = email_bcc or [] body = body or u'' msg = EmailMessage(policy=email.policy.SMTP) msg.set_charset('utf-8') if not message_id: if object_id: message_id = tools.generate_tracking_message_id(object_id) else: message_id = make_msgid() msg['Message-Id'] = message_id if references: msg['references'] = references msg['Subject'] = subject msg['From'] = email_from del msg['Reply-To'] msg['Reply-To'] = reply_to or email_from msg['To'] = email_to if email_cc: msg['Cc'] = email_cc if email_bcc: msg['Bcc'] = email_bcc msg['Date'] = datetime.datetime.utcnow() for key, value in headers.items(): msg[pycompat.to_text(ustr(key))] = value email_body = ustr(body) if subtype == 'html' and not body_alternative: msg.add_alternative(tools.html2plaintext(email_body), subtype='plain', charset='utf-8') msg.add_alternative(email_body, subtype=subtype, charset='utf-8') elif body_alternative: msg.add_alternative(ustr(body_alternative), subtype=subtype_alternative, charset='utf-8') msg.add_alternative(email_body, subtype=subtype, charset='utf-8') else: msg.set_content(email_body, subtype=subtype, charset='utf-8') if attachments: for (fname, fcontent, mime) in attachments: maintype, subtype = mime.split('/') if mime and '/' in mime else ('application', 'octet-stream') msg.add_attachment(fcontent, maintype, subtype, filename=fname) return msg
product_price_print() the_product_is_cheaper = True iterations = 0 while the_product_is_cheaper: time.sleep(0) minute = 0 iteration = 0 # If the target of the product is less than 4000, then It'll send the message if the_product_is_cheaper == True and product <= 4000: #Sending the message subject = f"{product} are on {price}!!!" body = f"\n\n{product_price_print()}\n\n Your python bot (:" # build-up email details using email.message module message = EmailMessage() message["Subject"] = subject message["From"] = my_email message["To"] = recipient message.set_content(body) # send the message via smtp using details above with smtplib.SMTP("smtp.gmail.com", port=587) as connection: connection.starttls() connection.login(my_email, password=password) connection.send_message(message) the_product_is_cheaper = False
def mail_results(dates=[], dryrun=False): if not os.path.exists(MAIL_TO_ADDRS_FILE): log.error( "Unable to email results since mail_to_addrs.txt is missing.") mail_to_addrs = [] try: with open(MAIL_TO_ADDRS_FILE) as f: for addr in f: mail_to_addrs.append(addr.strip()) if not len(mail_to_addrs): raise OSError("File is empty: {}".format(MAIL_TO_ADDRS_FILE)) for addr in mail_to_addrs: if '@' not in addr: raise ValueError( "Malformed email address in {}: {}".format( MAIL_TO_ADDRS_FILE, addr)) except FileNotFoundError as e: log.error("File is missing: {}".format(MAIL_TO_ADDRS_FILE)) log.error("See MAIL_TO_ADDRS in .env.".format(MAIL_TO_ADDRS_FILE)) sys.exit(1) except OSError as e: log.error(e.__str__()) sys.exit(1) except ValueError as e: log.error(e.__str__()) dryrun_subject_text = '[DRYRUN] ' if dryrun else '' total_success = len([d for d in dates if d['success']]) == len(dates) if len(dates): date_list_str = ', '.join( ['{}/{}'.format(d['year'], d['jd']) for d in dates]) date_list_str = ' (' + date_list_str + ')' else: date_list_str = '' if total_success: subject_text = "{}FW2 Product Generation{}".format( dryrun_subject_text, date_list_str).rstrip() body_text = "Success! See attached log for details." else: subject_text = "{}FAILED: FW2 Product Generation{}".format( dryrun_subject_text, date_list_str).rstrip() body_text = "Something went wrong... Usually this just means the most recent NRT tiles are missing from the GIMMS server. We'll try again in a bit." body_text += "\n\n" if len(dates): body_text += "Summary:\n\n" for d in dates: status_text = "OK" if d['success'] else "FAILED" body_text += "Product: {} / {}\n".format(d['year'], d['jd']) body_text += "Status: {}\n".format("OK" if d['success'] else "FAILED") body_text += "\n" log_path = get_log_path() if log_path: with open(log_path) as f: log_contents = f.read() else: log_contents = "Log file is missing!" log.info("Emailing results to {}".format(', '.join(mail_to_addrs))) msg = EmailMessage() me = '*****@*****.**' msg['Subject'] = subject_text msg['From'] = me msg['To'] = ', '.join(mail_to_addrs) msg.set_content(body_text) msg.add_attachment(log_contents, filename=os.path.basename(log_path)) s = smtplib.SMTP('localhost', 25) s.send_message(msg) s.quit()
css_class_of_cur_price = row[4].value crawls_per_day = row[5].value try: email_addresses = row[6].value.split(',') except AttributeError: email_addresses = '' if email_addresses: print(url) r = requests.get(url, headers=headers) tree = html.fromstring(r.text) current_price = int( float( tree.xpath('//*[@*="{}"]/text()'.format( css_class_of_cur_price))[-1].strip().replace('$', ''))) if current_price <= min_price_for_alert or current_price >= max_price_for_alert: for email_address in email_addresses: print(email_address) subject_message = "Price limit reached for {}. Current price is {}".format( product_name, current_price) message = "{} isimli ürün {}\'i adresinde {} TL'nin altında {} TL'ye satılıyor.".format( product_name, url, min_price_for_alert, current_price) msg = EmailMessage() msg.set_content(message) msg['Subject'] = subject_message msg['From'] = your_email msg['To'] = email_address server.send_message(msg) print("Message Sent to {}".format(email_address)) print(time.ctime()) time.sleep(43200)
import smtplib from email.message import EmailMessage msg = EmailMessage() msg['Subject'] = "Automated mail from python" msg["From"] = '*****@*****.**' msg['To'] = '*****@*****.**' msg.set_content('Hi, this is a automated mail from python') with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.login('*****@*****.**', 'app_password_from_google') smtp.send_message(msg)
msg['From'] = EMAIL_ADDRESS msg['To'] = emails #url from NewsAPI url = f"https://newsapi.org/v2/top-headlines?country=us&{API_KEY}" response = requests.get(url) articles = response.json()['articles'] news_email = "" news_sms = "" #looping through each all the articles and adding it to the string for i, article in enumerate(articles, 1): news_email += (f"{i}. {article['title']}\n") msg.set_content(news_email) #looping through top 15 news for the SMS for i, article in enumerate(articles, 1): if i < 11: news_sms += (f"{i}. {article['title']}\n") #email using SMTP def send_email(): with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD) smtp.send_message(msg) #print(news_sms)
import smtplib from email.message import EmailMessage username = '******' password = '******' contacts = ['*****@*****.**'] msg = EmailMessage() msg['Subject'] = 'This is a test' msg['From'] = username msg['To'] = contacts name = 'Aamir' msg.set_content('Plain Text Message') html_msg = """\ <!DOCTYPE html> <html> <body> <h1 style="color:SlateGray;">This is an HTML Email! {name}</h1> </body> </html> """.format(name=name) msg.add_alternative(html_msg, subtype='html') with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.login(username, password) smtp.send_message(msg)
def run(self, dispatcher, tracker, domain): print("im mailing action ...........") loc = tracker.get_slot('location') cuisine = tracker.get_slot('cuisine') price = tracker.get_slot('price') print(f"Im action send mail func: {loc}-{cuisine}-{price}") # check for non empty slots if not loc: dispatcher.utter_message(f"=> Please Specify City Name") return if not price: dispatcher.utter_message( f"=> Please Specify Price Range for Average Cost for two.") return if not cuisine: dispatcher.utter_message(f"=> Please Specify Cuisine type.") return # check for specific strings for Range/type of Entity for Slot filling and returning valid and non empty output. if loc.lower() not in WeOperate: dispatcher.utter_message(f"We do not operate in {loc} yet") return if cuisine.lower() not in OurCuisine: dispatcher.utter_message(f"We do not serve {cuisine} cuisine yet") return if price not in OurPricRanges: dispatcher.utter_message( f"Please select price in ranges: 1. Lesser than Rs. 300\n2. Rs. 300 to 700\n3. More than 700" ) return results = get_results(loc, cuisine, price) print(f"Results of get_results func: {results}") response = "\n" print(type(results)) if results.empty: response = " Sorry this combination does not exist." dispatcher.utter_message("=> " + response) else: for restaurant in results[:10].iterrows(): response = response + f"{restaurant[1][0]} in {restaurant[1][1]} costs {restaurant[1][2]} on average for two and has been rated {restaurant[1][3]}\n\n" # sender auth details for login sender = '*****@*****.**' sender_password = '******' # Message msg = EmailMessage() msg.set_content( f"This Message contains top Restaurants for your query: \n\n {response} \n\nThanks\nFoodie Bot" ) msg['Subject'] = 'Top 10 Restaurants of your preference.' msg['From'] = '*****@*****.**' msg['To'] = tracker.get_slot('mail_id') # send mail try: server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(sender, sender_password) print("Login Success.") server.send_message(msg) server.close() dispatcher.utter_message("=> " + "Emailed you Successfully, Thanks.") except SMTPException as e: print("Email Cannot be Sent, Thanks.", e) dispatcher.utter_message("=> " + "Invalid email.")
import smtplib import os from email.message import EmailMessage import imghdr email_address = '*****@*****.**' email_password = os.environ.get('EMAIL_PSWD') msg = EmailMessage() msg.set_content('Files attached...') msg['Subject'] = 'Hey buddy check my files' msg['From'] = email_address msg['To'] = email_address files = ['sample.txt'] for file in files: with open(file, 'rb') as f: file_data = f.read() file_name = f.name msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name) with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.login(email_address, email_password) smtp.send_message(msg)
def send(self): from email.message import EmailMessage from email.utils import COMMASPACE import mimetypes import smtplib msg = EmailMessage() if self.errors: error_msg = '\n\n'.join([str(x) for x in self.errors]) if 'body_error' not in self.options['email']: body = self.default_body_error else: body = self.options['email']['body_error'] msg.set_content( arbiter.parse_string(body, errors=' '.join(error_msg))) else: msg.set_content(arbiter.parse_string( self.options['email']['body'])) # write headers for k in self.options['email']: if k in self._emailheaders: if isinstance(self.options['email'][k], list): msg[k] = arbiter.parse_string( COMMASPACE.join(self.options['email'][k])) else: msg[k] = arbiter.parse_string(self.options['email'][k]) # attach files for file in self.files: ctype, encoding = mimetypes.guess_type(file) # unknown, treat as binary if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) with open(file, 'rb') as fp: msg.add_attachment(fp.read(), maintype=maintype, subtype=subtype, filename=os.path.basename(file)) if self.options['smtp'].get('ssl', False): klass = smtplib.SMTP_SSL elif self.options['smtp'].get('lmtp', False): klass = smtplib.LMTP else: klass = smtplib.SMTP with klass(host=self.options['smtp']['host'], **self.__smtp_options()) as smtp: if self.options['smtp'].get('tls', False): tlsargs = { x: self.options['smtp'][x] for x in self.options['smtp'] if x in ['keyfile', 'certfile'] } smtp.starttls(**tlsargs) if self.options['smtp'].get('username', None) \ and self.options['smtp'].get('password', None): smtp.login(self.options['smtp']['username'], self.options['smtp']['password']) smtp.send_message(msg)
import smtplib from email.message import EmailMessage # import getpass # password = getpass.getpass('비밀번호뭐니?') email_list = ['*****@*****.**', '*****@*****.**'] for email in email_list: msg = EmailMessage() msg['Subject'] = "안녕하세요 저는 서희수입니다!!" msg['From'] = "*****@*****.**" msg['To'] = email msg.set_content(email + '에게 메일을 보냈습니다!!') smtp_url = 'smtp.naver.com' smtp_port = 465 s = smtplib.SMTP_SSL(smtp_url, smtp_port) s.login('seoheesu81','GMLTN6257') s.send_message(msg)
import smtplib import os import imghdr from email.message import EmailMessage EMAIL_ADDRESS = os.environ.get('EMAIL_ADDRESS') EMAIL_PASSWORD = os.environ.get('EMAIL_PASSWORD') msg = EmailMessage() msg['Subject'] = "Check out pictures!" msg['From'] = EMAIL_ADDRESS msg['To'] = '*****@*****.**' msg.set_content('Images attached...') files = ['logo.jfif', 'profile_pic.jpg'] for file in files: with open(file, 'rb') as f: file_data = f.read() file_type = imghdr.what(f.name) file_name = f.name Sending Images msg.add_attachment(file_data, maintype='image', subtype=file_type, filename=file_name) with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD) smtp.send_message(msg)
# Import smtplib for the actual sending function import smtplib # Import the email modules we'll need from email.message import EmailMessage # Open the plain text file whose name is in textfile for reading. msg = EmailMessage() msg.set_content("""textanfang textende """) # me == the sender's email address # you == the recipient's email address msg['Subject'] = 'Betreff' msg['From'] = '*****@*****.**' msg['To'] = '*****@*****.**' # Send the message via our own SMTP server. s = smtplib.SMTP('mail.gmx.de') s.starttls() username = input("Username? ") password = input("password? ") s.login(username, password) s.send_message(msg) s.quit()
def message_me(method='email', time_threshold=1, email_address=os.environ.get('gmail_address'), email_password=os.environ.get('MPL_gmail_password'), account_sid=os.environ.get('account_sid'), authorisation_token=os.environ.get('authorisation_token'), from_whatsapp_number=os.environ.get('from_whatsapp_number'), to_whatsapp_number=os.environ.get('to_whatsapp_number')): #### (1) Determine whether the user has practiced their instrument recently. # Determine the full file path for our log data. cwd = os.getcwd() log_data_directory = cwd.replace('music-practice-log', 'log-data') log_data_path = os.path.join(log_data_directory, 'log.csv') # Determine how long it's been since our last log entry. previous_data = pd.read_csv(log_data_path) previous_data['Date (datetime object)'] = pd.to_datetime( previous_data['Date (DMY)'], format='%d/%m/%Y') last_entry = previous_data['Date (datetime object)'][ len(previous_data) - 1].to_pydatetime().date() today = date.today() total_days_since_last_entry = ( today.day + (today.month * 30) + (today.year * 365)) - (last_entry.day + (last_entry.month * 30) + (last_entry.year * 365)) #### (2) Create a list of potential WhatsApp messages. messages = [ "Ahoy there, Sam. You haven't been able to get some banjo in recently! Have a look at this video to get psyched: https://www.youtube.com/watch?v=-3Y7F5JJRcM", "Oh,\n What's occurin,\n Play the Banjo ya noooob.", "Mi amigo, this is a reminder to keep up the banjo playing and the banjo logging. The graph must grow!", "You should practice because Laura says: 'I think it's really hot when you play the banjo well'. Take from that what you will.", "Imagine how awesome it'll be when you can play along at folk nights on the banjo! Keep up the good work.", "Hello there, banjo enthusiast! Here's a good song to get you excited for frailing again: https://www.youtube.com/watch?v=X9Rfm3_kJhM", "From Laura: 'You can doeth the do Bebe! Grab that Banjo and get strumming.'", "Here's the song that started it all: https://www.youtube.com/watch?v=xzt8WxXtVmM", "If it's late, or you're tired, remember that clawhammer can be relaxing. Have a listen to this: https://www.youtube.com/watch?v=POZDdac7wHU&list=PLyiQRVof2bGsj2kt_irm6wMgQxoq7jmOK", "You are not machines! You are not cattle! You are men! You have the love of humanity in your hearts! You don’t hate! Only the unloved hate - the unloved and the unnatural! Soldiers! Don’t fight for slavery! Fight for liberty! And play the banjo!", "Keep calm and play the banjo.", "When was the last time you played the banjo?\nJust for the sake of it\nAnd have you ever played the banjo just because it was a banjo and you have two good hands?\nSome people will say\n'You need sheet music'\nBut there is nothing wrong with not knowing what you are playing\nLots of people going around these day\nNot playing their instruments\nGo on any train, bus, plane\nAnd you'll see people who have stopped playing their instruments\nDon't be one of them\nYou may say\n'I've practiced this piece before' and that's ok\nBut creativity is never gone\nPractice they say is without fun\nBut I have never seen your banjo playing itself \nOn any secret corner\nYou may find the tune of your life, the sound of your soul\nThe rhythm of your day, the chord of your smile\nOr maybe not\nBut you may find something you've not heard before\nOf course, not all these practices can be magic practices that stun and amaze\nBut possible you may find a lonely piece that sings and cures\nOr even better you might find peace\nThat world that's on your computer is not the world\nThe world is the one that lies in the sounds your strings make\nAnd the smiles that they create\nThe dances, the vibes, the joys they emulate\nTell the world you are playing and it replies\nYou see I'm not sure what the secret to happiness is\nBut I'm pretty sure it starts when you play your banjo" ] random_message_idx = random.randint(0, len(messages)) #### (3) Send one of the messages to the user. if total_days_since_last_entry > time_threshold: #### (3a) Send a WhatsApp message. if method == 'WhatsApp': # Push the graph to GitHub. PATH_OF_GIT_REPO = r'C:\Users\Samuel Huguet\OneDrive\Documents\Personal\Music-Practice-Log' # make sure .git folder is properly configured COMMIT_MESSAGE = 'Updated graph and log file' try: repo = Repo(PATH_OF_GIT_REPO) repo.git.add(update=True) repo.index.commit(COMMIT_MESSAGE) origin = repo.remote(name='origin') origin.push() except: print('Some error occured while pushing the code') client = Client(account_sid, authorisation_token) from_whatsapp_number = 'whatsapp:' + from_whatsapp_number to_whatsapp_number = 'whatsapp:' + to_whatsapp_number client.messages.create( body=messages[random_message_idx], MediaUrl= 'https://github.com/SamHSoftware/Music-Practice-Log/blob/main/log-data/log.png?raw=true', from_=from_whatsapp_number, to=to_whatsapp_number) #### (3b) Send an email. elif method == 'email': # Write the e-mail. message = EmailMessage() message['Subject'] = 'Practice update' message['From'] = email_address message['To'] = email_address main_content = f'{messages[random_message_idx]}\n\nHere is a the graph displaying your practice over time:' message.set_content(main_content) # Include the graph within the e-mail. cwd = os.getcwd() log_data_directory = cwd.replace('music-practice-log', 'log-data') file_directory = os.path.join(log_data_directory, 'log.png') with open(file_directory, 'rb') as f: file_data = f.read() file_type = imghdr.what(f.name) file_name = f.name message.add_attachment(file_data, maintype='image', subtype=file_type, filename=file_name) # Define an SMTP client session object that can be used to send an email. with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.login(email_address, email_password) smtp.send_message(message)
duration_h, duration_m = divmod(duration, 60) print("TIME'S UP") print("The setting time is {:02d} : {:02d}".format(hours_copy, minutes_copy)) print("The running time is {:02d} : {:02d}".format(int(duration_h), int(duration_m))) # 邮件提醒服务 if mail_notice == "y": sender = "*****@*****.**" pwd = "notification" # 构建邮件 msg = EmailMessage() msg.set_content( "TIME'S UP\nThe setting time is {:02d} : {:02d}\nThe running time is {:02d} : {:02d}" .format(hours_copy, minutes_copy, int(duration_h), int(duration_m))) msg["Subject"] = "TIME'S UP" msg["From"] = sender msg["To"] = receiver try: # 建立SMTP连接 smtpObj = smtplib.SMTP(host="smtp.gmail.com", port=587) # 不需要显式调用smtplib.ehlo()方法 smtpObj.starttls() # 加密连接 smtpObj.login(sender, pwd) smtpObj.sendmail(sender, receiver, msg.as_string()) finally: smtpObj.quit()
import smtplib from email.message import EmailMessage from string import Template from pathlib import Path html = Template(Path('index.html').read_text()) email = EmailMessage() email['from'] = 'Muhammad Talha' email['to'] = '*****@*****.**' email['subject'] = 'You won 1,000,000 dollars!' email.set_content(html.substitute({'name': 'Talha'}), 'html') with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp: smtp.ehlo() smtp.starttls() smtp.login('your email', 'password') smtp.send_message(email) print('all good boss!')
# Check if we found a password in the regular expression. All wifi connections will not have passwords. if password == None: wifi_profile["password"] = None else: # We assign the grouping (Where the password is contained) we are interested to the password key in the dictionary. wifi_profile["password"] = password[1] # We append the wifi information to the wifi_list wifi_list.append(wifi_profile) # Create the message for the email email_message = "" for item in wifi_list: email_message += f"SSID: {item['ssid']}, Password: {item['password']}\n" # Create EmailMessage Object msg = EmailMessage() recipients=["your email id "] msg['From'] = "your name" msg['To'] = ", ".join(recipients) msg['Subject'] = 'List of wifi password' msg.set_content(email_message) # Send the message via our own SMTP server. login_id ="Your email id" login_pass ="******" #app key different for every person server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.login(login_id,login_pass) # print("login successfully") server.send_message(msg) # print("Email is successfully sent") server.quit()
import smtplib from email.message import EmailMessage email = EmailMessage() email['from'] = 'Sender' email['to'] = '*****@*****.**' email['subject'] = 'You won 1,000,000 dollars!' email.set_content('I am a python master') with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp: smtp.ehlo() smtp.starttls() smtp.login('*****@*****.**', 'account_password') smtp.send_message(email) print('Message Sent')
import smtplib # this is needed to send emails from email.message import EmailMessage from string import Template from pathlib import Path # similar to os.path to acceess another file html = Template(Path('index.html').read_text()) email = EmailMessage() email['from'] = 'Alexander Medina' email['to'] = '*****@*****.**' email['subject'] = 'You won 1,000,000 dollars' email.set_content(html.substitute({'name': 'alex'}), 'html') with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp: smtp.ehlo() # starts the server smtp.starttls() # this is the encryption smtp.login('*****@*****.**', 'Am0955667') smtp.send_message(email) print('all good boss')
if __name__ == "__main__": notification = sys.argv[1] pemails = sys.argv[2] plogtype = sys.argv[3] # ex 'qa' 'export' '*' (latest) logdir = os.environ['TARGETLOGDIR'] emailfrom = os.environ['NOTIFYFROM'] smtpfrom = os.environ['SMTPFROM'] msg = EmailMessage() # content is like "importing buildings onto xxx.sde" content = 'Completed {0} '.format(notification) msg['Subject'] = content content += 'at {0} {1}'.format(datetime.datetime.now(), os.linesep) content += getlogfile(logdir, plogtype) msg.set_content(content) msg['From'] = emailfrom # this is headers only # if a string is passed to sendmail it is treated as a list with one element! msg['To'] = pemails smtp = smtplib.SMTP(smtpfrom) smtp.sendmail(msg['From'], msg['To'].split(","), msg.as_string()) smtp.quit()
# if running, exit script if samba_state() != -1: quit() # else restart up to five times unless unsucessful else: for i in range(1, 5): subprocess.check_output(['service', 'smbd', 'status']) if samba_state() == -1: quit() # else email to prompt fix ############# need to check if email has been recently sent or problem fixed sender_email = os.environ.get('SMBD_MONITOR_SEND_EMAIL') sender_password = os.environ.get('SMBD_MONITOR_SEND_PASSWORD') receiver_email = os.environ.get('SMBD_MONITOR_RECEIVE_EMAIL') port = 465 context = ssl.create_default_context() with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server: server.login(sender_email, sender_password) msg = EmailMessage() msg.set_content('') msg['Subject'] = 'Server down: Samba' msg['From'] = sender_email msg['To'] = receiver_email server.sendmail(sender_email, receiver_email, msg)
import os import smtplib from email.message import EmailMessage EMAIL_ADDRESS = os.environ.get('EMAIL_USER') EMAIL_PASSWORD = os.environ.get('EMAIL_PASS') msg = EmailMessage() msg['Subject'] = 'Grab dinner this weekend?' msg['From'] = EMAIL_ADDRESS msg['To'] = '*****@*****.**' msg.set_content('How about dinner at 6pm this Staturday?') with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD) smtp.send_message(msg)