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 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): # 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 add_attachment(cls, msg: EmailMessage, content: bytes, filename: str, mimetype: str = None): """ Add binary data as an attachment to an :class:`~email.message.EmailMessage`. The default value for the ``mimetype`` argument is guessed from the file name. If guessing fails, ``application/octet-stream`` is used. :param msg: the message :param content: the contents of the attachment :param filename: the displayed file name in the message :param mimetype: the MIME type indicating the type of the file """ assert check_argument_types() if not mimetype: mimetype, _encoding = guess_type(filename, False) if not mimetype: mimetype = 'application/octet-stream' maintype, subtype = mimetype.split('/', 1) if not maintype or not subtype: raise ValueError('mimetype must be a string in the "maintype/subtype" format') msg.add_attachment(content, maintype=maintype, subtype=subtype, filename=filename)
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
class MHTML(object): def __init__(self): self._msg = EmailMessage() self._msg['MIME-Version'] = '1.0' self._msg.add_header('Content-Type', 'multipart/related', type='text/html') def add(self, location: str, content_type: str, payload: str, encoding: str = 'quoted-printable') -> None: resource = EmailMessage() if content_type == 'text/html': resource.add_header('Content-Type', 'text/html', charset='utf-8') else: resource['Content-Type'] = content_type if encoding == 'quoted-printable': resource['Content-Transfer-Encoding'] = encoding resource.set_payload(quopri.encodestring(payload.encode())) elif encoding == 'base64': resource['Content-Transfer-Encoding'] = encoding resource.set_payload(base64.b64encode(payload)) elif encoding == 'base64-encoded': # Already base64 encoded resource['Content-Transfer-Encoding'] = 'base64' resource.set_payload(payload) else: raise ValueError('invalid encoding') resource['Content-Location'] = location self._msg.attach(resource) def __str__(self) -> str: return str(self._msg) def __bytes__(self) -> bytes: return bytes(self._msg)
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 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 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 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 main(): parser = ArgumentParser(description="""\ Send the contents of a directory as a MIME message. 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. """) parser.add_argument('-d', '--directory', help="""Mail the contents of the specified directory, otherwise use the current directory. Only the regular files in the directory are sent, and we don't recurse to subdirectories.""") parser.add_argument('-o', '--output', metavar='FILE', help="""Print the composed message to FILE instead of sending the message to the SMTP server.""") parser.add_argument('-s', '--sender', required=True, help='The value of the From: header (required)') parser.add_argument('-r', '--recipient', required=True, action='append', metavar='RECIPIENT', default=[], dest='recipients', help='A To: header value (at least one required)') args = parser.parse_args() directory = args.directory if not directory: directory = '.' # Create the message msg = EmailMessage() msg['Subject'] = 'Contents of directory %s' % os.path.abspath(directory) msg['To'] = ', '.join(args.recipients) msg['From'] = args.sender msg.preamble = 'You will not see this in a MIME-aware mail reader.\n' for filename in os.listdir(directory): path = os.path.join(directory, filename) if not os.path.isfile(path): continue # Guess the content type based on the file's extension. Encoding # will be ignored, although we should check for simple things like # gzip'd or compressed files. ctype, encoding = mimetypes.guess_type(path) 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) with open(path, 'rb') as fp: msg.add_attachment(fp.read(), maintype=maintype, subtype=subtype, filename=filename) # Now send or store the message if args.output: with open(args.output, 'wb') as fp: fp.write(msg.as_bytes(policy=SMTP)) else: with smtplib.SMTP('localhost') as s: s.send_message(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 combine(body, attachments): message = EmailMessage() message.add_related(body, subtype='html') for attachment in attachments: cid = attachment['cid'] buffer = attachment['buffer'] img = MIMEImage(buffer.read(), _subtype='png') img.add_header('Content-ID', cid) message.attach(img) return message
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 convert(filename): with open(filename, "r") as file: raws = file.read().split("\n") subject = raws[0] body = "\n".join(raws[1:]) email = EmailMessage() email.set_payload(body,"utf8") email["Subject"] = subject return email
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_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 _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 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 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 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 compile(self): if len(self.parts) == 1 and isinstance(self.parts[0], str): msg = txt2mail(self.parts[0]) else: msg = EmailMessage(policy=POLICY) # This currently doesn't work <https://bugs.python.org/issue30820>: #msg.set_content([ # txt2mail(p) if isinstance(p, str) else p for p in self.parts #]) msg.make_mixed() for p in self.parts: msg.attach(txt2mail(p) if isinstance(p, str) else p) for k,v in self.headers.items(): msg[k] = v return msg
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()
temps.append(forcast_3hour['main']['temp']) if forcast_3hour['weather'][0]['icon'] in rain_or_snow_icons: rain_or_snow.append(forcast_3hour['weather'][0]['icon']) min_temp = min(temps) if min_temp > 60: clothes_style = 'summer' elif min_temp > 30: clothes_style = 'fall/spring' else: clothes_style = 'winter' with open(email_configfile_path) as data: email_config = json.loads(data.read()) msg = EmailMessage() msg.set_content(clothes_style) msg['From'] = email_config['from'] msg['To'] = email_config['to'] if rain_or_snow: storm_picture_url = 'http://openweathermap.org/img/w/'+rain_or_snow[0]+'.png' r2 = requests.get(storm_picture_url) img_data = r2.content msg.add_attachment(img_data, maintype='image', subtype=imghdr.what(None, img_data)) with smtplib.SMTP('smtp.gmail.com', 587) as s: s.ehlo() s.starttls() s.login(email_config['from'],email_config['pwd']) s.send_message(msg)
def test_get_message_id(self): msg = EmailMessage() msg["Message-Id"] = '<%s>' % ('x' * 300) self.assertEqual(utils.get_message_id(msg), 'x' * 254)
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 combintion 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) 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(html2text.html2text(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
def reset(self): with open("Temp2.txt", "r+") as file: self.read1 = file.read() #print(self.read1) self.passw = self.pass_.get() self.passconw = self.passcon.get() self.current2_ = self.current_.get() self.phone_2 = self.phone_.get() self.conn = sqlite3.connect("bakery.db") self.c = self.conn.cursor() self.c.execute("SELECT Password from admin WHERE Phone_No=" + self.phone_2) self.data = self.c.fetchall() if self.data == []: return messagebox.showerror( "Error", " Current Password not Matched to Your mail Id", parent=self.root2) else: for i in self.data: #print(i[0]) if i[0] == self.current2_: self.OTP_Forget = str(random.randint(100000, 999999)) send = smtplib.SMTP("smtp.gmail.com", 587) # Create session for Gmail send.starttls() # transport layer msg = EmailMessage() msg["Subject"] = "OTP" msg["From"] = "*****@*****.**" msg["To"] = self.read1 msg.set_content("Hi! your OTP for reset password: "******"\'" + str(self.OTP_Forget) + "\'") try: send.login("your Email Id", "Your Password") except smtplib.SMTPAuthenticationError: messagebox.showerror("Error", "Error Occur Otp Not") try: try: try: send.send_message(msg) messagebox.showinfo( "Mailed", "OTP Sent to Your Mail Id") self.root2.destroy() self.root3 = Toplevel( root ) # Child Window "Tk() can Also be use here" self.root3.title("Verification") self.root3.geometry("750x320+350+150") self.root3.configure(bg="black") photo4 = ImageTk.PhotoImage( file="Pics\\bakeryicon.jpg") self.root3.iconphoto(False, photo4) self.root3.grab_set() self.root3.resizable(False, False) title_child = Label( self.root3, text="Reset Password", bg="#152238", fg="white", compound=LEFT, font=("Goudy Old Style", 48, "bold"), anchor="w").place(x=0, y=0, relwidth=1) otp_lbl = Label(self.root3, text="Enter OTP", font=("time new roman", 18, "bold"), fg="white", bg="black").place(x=30, y=120) self.otp_ = Entry(self.root3, bd=5, width=30, bg="lightgrey", font=("times new roman", 18)) self.otp_.place(x=260, y=120) Reset_btn = Button(self.root3, text="Reset", font=("times new roman", 18, "bold"), activebackground="blue", activeforeground="white", bg="blue", fg="white", cursor="hand2", command=self.reset1) Reset_btn.place(x=495, y=260, width=140, height=30) except smtplib.SMTPRecipientsRefused: messagebox.showerror("Mailed", "Mail Not Sent") except smtplib.SMTPException: messagebox.showerror("Mailed", "Mail Not Sent") except smtplib.SMTPConnectError: messagebox.showerror("Error", "Connection Error") else: return messagebox.showerror( "Error", "Contact No. have not given Mail Id")
import os # Environment variables b/c email and pass is stored elsewhere. import smtplib # Simple mail transfer protocol. Used to send emails to any internet machine. import imghdr # Helps with multiple image attachments and helps determine what type of image. from email.message import EmailMessage # EmailMessage is an object that makes it easier to format emails. EMAIL_ADDRESS = os.environ.get( 'EMAIL_USER') # Email address environment variable. EMAIL_PASSWORD = os.environ.get( 'EMAIL_PASS') # Email password environment variable. contacts = ['*****@*****.**'] # Add comma and more emails. # Emails informations: msg = EmailMessage() msg['Subject'] = 'Blahbity blah blah' msg['From'] = EMAIL_ADDRESS msg['To'] = ', '.join(contacts) msg.set_content('This is a plain text email.') # For HTML email: (You can make your email prettier if you like.) msg.add_alternative("""\ <!DOCTYPE> <html> <body> <h1 style="color:SlateGray;"> This is an HTML email.</h1> </body> </html> """, subtype='html') # Multiple image files:
import smtplib from email.message import EmailMessage email = EmailMessage() email['from'] = 'Sevag B' 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('*****@*****.**', 'sev19boghoss') smtp.send_message(email) print('all good boss!')
'Floor Plan Amenities': floorPlanAmenities, # 'Timestamp': datetime.now().strftime("%d/%m/%Y %H:%M:%S") } driver.execute_script("window.history.go(-1)") WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[contains(@id, 'property')]"))) time.sleep(4) element = driver.find_element_by_xpath(f"(//div[contains(@id, 'property')])[{count_outer}]") driver.execute_script("return arguments[0].scrollIntoView(true);", element) time.sleep(3) driver.execute_script("scrollBy(0,100);") time.sleep(5) except: self.sendMail('SCRAPER ERROR ALERT: iret apartments', f'Hi,\niret scraper encountered an error at {datetime.now().strftime("%d/%m/%Y %H:%M:%S")}\nThe scraping job was initiated at {self.init_time}\nThe error is "Else part of the parse function failed with some unexcepted error".\nPlease see more information here: /home/p.byom26/residentialReits/rrScrapers/iretApartments/iretApartments/spiders/iret.py\nContact [email protected] for help.\n\nSent From\nGCP Ubuntu VM') os._exit(1) except Exception: EMAIL_USER = os.environ.get('EMAIL_USER') EMAIL_PASS = os.environ.get('EMAIL_PASS') msg = EmailMessage() msg['Subject'] = 'SCRAPER ERROR ALERT: iret apartments' msg['From'] = EMAIL_USER msg['To'] = '[email protected], [email protected]' msg.set_content(f'Hi,\niret apartments scraper encountered an error at {datetime.now().strftime("%d/%m/%Y %H:%M:%S")}\nThe scraping job was initiated at {init_time_outer}\nThe error is "An Unexcepted Error Occured".\nPlease see more information here: /home/p.byom26/residentialReits/rrScrapers/iretApartments/iretApartments/spiders/iret.py\nContact [email protected] for help.\n\nSent From\nGCP Ubuntu VM') with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.login(EMAIL_USER, EMAIL_PASS) smtp.send_message(msg)
#pop3_server = input('POP3 server: ') # connect to pop3 server: host = 'outlook.office365.com' port = 995 s = smtplib.STMP_SSL(host, port) s.set_debuglevel(2) # user account authentication #server.user("*****@*****.**") #server.pass_("asdfgh5678") s.login(user, password) from_addr = user to_addrs = input('To who? : ') with open(textfile) as fp: email = EmailMessage() email.set_content(fp.read()) email['Subject'] = "relatórios dos técnicos" email['From'] = from_addr email['To'] = "*****@*****.**" #curl -i 'https://helpticket-e00ce.firebaseio.com/tickets.json?orderBy="idTechnician"&equalTo="currentUserId" #select orderBy #'https://dinosaur-facts.firebaseio.com/dinosaurs.json?orderBy="height"&startAt=3&print=pretty' #orderByChild("idTechnician").equalTo(currentUserId).orderByChild("requested_date").equalTo(currentDate.getTime().toString()).limitToFirst(1); msg = email s.sendmail(from_addr, to_addrs, msg)
import smtplib from email.message import EmailMessage #this is needed to create an email subject email = EmailMessage() email['From'] = '*****@*****.**' email['To'] = '*****@*****.**' email['Subject'] = 'Diesmal mit Betreff' email.set_content('Hallo\ndies ist nur ein Test.') #now let's attach the first pdf with open('C:\\Users\\...\\Emailstuff\\periodictable.pdf', 'rb') as m: file_data = m.read() file_name = "periodictable.pdf" #you can choose a name for the receiver to see here email.add_attachment(file_data, maintype='image', subtype='octet-stream', filename=file_name) #now let's attach another pdf with open('C:\\Users\\...\\Emailstuff\\another_attachment.pdf', 'rb') as m: file_data = m.read() file_name = "another_attachment.pdf" #you can choose a name for the receiver to see here email.add_attachment(file_data, maintype='image', subtype='octet-stream', filename=file_name)
import smtplib import imghdr from email.message import EmailMessage EMAIL_ADDRESS = '*****@*****.**' EMAIL_PASSWORD = '******' msg = EmailMessage() msg['Subject'] = "Grab Dinner" msg['From'] = EMAIL_ADDRESS msg['Reply-to'] = '*****@*****.**' msg['To'] = '*****@*****.**' msg.set_content("How About dinner at 6pm today") s = smtplib.SMTP_SSL('smtp.gmail.com', 465) # try: # s.ehlo() # s.starttls() # s.ehlo() # except: # pass s.login(EMAIL_ADDRESS, EMAIL_PASSWORD) s.send_message(msg) s.quit()
import smtplib from email.message import EmailMessage import getpass password = getpass.getpass('PASSWORD : '******'Subject'] = '월급내역서_2' msg['From'] = '^^' msg['To'] = '^^', '^^' msg.set_content('옛다 월급이다') ssafy = smtplib.SMTP_SSL('smtp.naver.com', 465) ssafy.login('^^', password) ssafy.send_message(msg) print('이메일 전송 완료!') # Delete personal information
import smtplib from email.message import EmailMessage from string import Template from pathlib import Path # html = Path('index.html').read_text() # s = Template(html) # s.substitute(name='piyush') html = Template(Path('index.html').read_text()) email = EmailMessage() email['from'] = 'Piyush Kumar' email['to'] = '*****@*****.**' email['subject'] = 'Verify your account' email.set_content(html.substitute(name='piyush'),'html') with smtplib.SMTP(host='smtp.gmail.com',port=587) as smtp: smtp.ehlo() smtp.starttls() smtp.login('*****@*****.**', 'james_bon007') smtp.send_message(email) print("all good!!!")
def send_mail(sender, message_content): # Create a secure SSL context context = ssl.create_default_context() try: server = smtplib.SMTP(settings['server'], settings['port']) server.starttls(context=context) # Secure the connection server.login(settings['login'], settings['password']) # Create email message and add headers (most of them are required to pass spam filters) message = EmailMessage() message.add_header('From', settings['fromaddr']) message.add_header('To', settings['toaddr']) message.add_header('Subject', SUBJECT) message.add_header('Date', formatdate()) message.add_header('Message-ID', make_msgid()) # Add optional Reply-To address if sender: message.add_header('Reply-To', sender) # Add message content message.set_content(message_content) # Send message server.send_message(message, from_addr=settings['fromaddr'], to_addrs=settings['toaddr']) print('Email sent successfully') except Exception as e: print(e) finally: server.quit()
def main(): parser = ArgumentParser(description="""\ Send the contents of a directory as a MIME message. 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. """) parser.add_argument('-d', '--directory', help="""Mail the contents of the specified directory, otherwise use the current directory. Only the regular files in the directory are sent, and we don't recurse to subdirectories.""") parser.add_argument('-o', '--output', metavar='FILE', help="""Print the composed message to FILE instead of sending the message to the SMTP server.""") parser.add_argument('-s', '--sender', required=True, help='The value of the From: header (required)') parser.add_argument('-r', '--recipient', required=True, action='append', metavar='RECIPIENT', default=[], dest='recipients', help='A To: header value (at least one required)') args = parser.parse_args() directory = args.directory if not directory: directory = '.' # Create the message msg = EmailMessage() msg['Subject'] = f'Contents of directory {os.path.abspath(directory)}' msg['To'] = ', '.join(args.recipients) msg['From'] = args.sender msg.preamble = 'You will not see this in a MIME-aware mail reader.\n' for filename in os.listdir(directory): path = os.path.join(directory, filename) if not os.path.isfile(path): continue # Guess the content type based on the file's extension. Encoding # will be ignored, although we should check for simple things like # gzip'd or compressed files. ctype, encoding = mimetypes.guess_type(path) 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) with open(path, 'rb') as fp: msg.add_attachment(fp.read(), maintype=maintype, subtype=subtype, filename=filename) # Now send or store the message if args.output: with open(args.output, 'wb') as fp: fp.write(msg.as_bytes(policy=SMTP)) else: with smtplib.SMTP('localhost') as s: s.send_message(msg)
def writeEmail(emailBody): msg = EmailMessage() msg.set_content(emailBody) return msg
def mail_service(email, password): from email.message import EmailMessage email_address = email email_password = password msg = EmailMessage() speak_devis('What is the subject of your message?') msg['Subject'] = record_audio() msg['From'] = email_address speak_devis('Who will you like to send the mail to?') receiver = popup('Email', 'Enter Recipient Email Address:') msg['To'] = receiver speak_devis( 'Please provide the content of the mail! Would you prefer to type it or say it?' ) while True: response = record_audio() if 'type' or "type it" in response: content = popup('Email Content', 'Type in the Content of Your Mail:') break elif 'speak' or "say it" in response: content = record_audio() break else: speak_devis( "I couldn't understand your response. Please use either the word type or speak!" ) continue msg.set_content(content) speak_devis(('Do you want to attach a file?')) attachcontent = record_audio() if attachcontent.lower() == 'yes': while True: try: speak_devis('How many files do you want to attach? ') attachcount = int(record_audio()) attachments = 0 while attachments < attachcount: file_path = fileExplorer() with open(file_path, 'rb') as f: file_data = f.read() file_mime = filetype.guess_mime(f.name) file_type = filetype.guess_extension(f.name) file_name = f.name.split('/')[-1] msg.add_attachment(file_data, maintype=file_mime, subtype=file_type, filename=file_name) attachments += 1 break except ValueError: speak_devis('You were meant to type a number.') continue except FileNotFoundError: speak_devis('File could not be accessed!') continue except Exception as e: speak_devis( "I ran into issues trying to process that. Let's try that again!" ) print(e) continue else: speak_devis('Message will be sent without an attachment!') with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.login(email_address, email_password) smtp.send_message(msg) speak_devis('Your email has been sent!') return
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'] = '*****@*****.**' msg['To'] = '*****@*****.**' msg.set_content('How about dinner at 6pm this saturday?') # added SSL and removed the smtp.ehlo() with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: # smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD) smtp.login("*****@*****.**", "letmein") # smtp.sendmail(SENDER, RECEIVER, msg) # smtp.sendmail(EMAIL_ADDRESS, '*****@*****.**', msg) smtp.send_message(msg)
#注意,这里的方法可能一段时间以后就不适用了,需要重新去网上搜索方法,这里用的是gmail #邮件带附件 import smtplib from email.message import EmailMessage import mimetypes import os,sys os.chdir(sys.path[0]) message = EmailMessage() sender = '*****@*****.**' receiver = '*****@*****.**' pswd = 'wa5' def send_email(xflie): message['From'] = sender message['To'] = receiver message['Subject'] = 'Subject line goes here' body_of_email = 'Text to be displayed in the email' message.set_content(body_of_email) mime_type, _ = mimetypes.guess_type(xflie) #不懂 mime_type, mime_subtype = mime_type.split('/') #不懂 with open(xflie, 'rb') as file:
import smtplib from email.message import EmailMessage print('Setup...') count = 0 server = smtplib.SMTP('smtp.gmail.com', 535 ) server.ehlo() server.starttls() server.ehlo() server.login('*****@*****.**', 'password') data = ['*****@*****.**'] for email in data: msg = EmailMessage() msg['Subject'] = 'Confirmation/RSVP for the MLH localhost' msg['From'] = '<from email>' msg['To'] = f"{email}" msg.set_content('Hey Hemu', subtype = 'html') server.send_message(msg) print('sent') count = count + 1 print(count)
import smtplib from email.message import EmailMessage email = EmailMessage() email['from'] = 'Prakhar Bajpai' email['to'] = 'Email' email['subject'] = 'you won 300000 prakhar' email.set_content('I am invatable') with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp: smtp.ehlo() smtp.starttls() smtp.login("your_email_id", "password") smtp.send_message(email) print("all good boss")
from flask import render_template, request, redirect, url_for, flash, g, session, current_app from passlib.hash import sha256_crypt from datetime import datetime, date from models import * from sqlalchemy import text from web3 import Web3 import os import json import secrets import smtplib from email.message import EmailMessage #------------EMAIL CONFIGURATION-----------------# EMAIL_ADDRESS = '*****@*****.**' EMAIL_PASSWORD = '******' msg = EmailMessage() #--------------END EMAIL CONFIGURATION------------# app = Flask(__name__) app.secret_key = 'charitySystem' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config[ 'SQLALCHEMY_DATABASE_URI'] = 'postgresql://*****:*****@localhost/CharitySystem' profileFolder = os.path.join('static', 'profileImages') app.config['UPLOAD_PROFILE_IMAGE_FOLDER'] = profileFolder ganache_url = "http://127.0.0.1:7545" web3 = Web3(Web3.HTTPProvider(ganache_url)) abi = json.loads( '[{"constant":true,"inputs":[],"name":"getBalance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"amt","type":"int256"}],"name":"sendEther","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"functionCalled","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"}]' )
import os import smtplib import imghdr from email.message import EmailMessage EMAIL_ADDRESS = os.environ.get('EMAIL_USER') EMAIL_PASSWORD = os.environ.get('EMAIL_PASS') msg = EmailMessage() msg['Subject'] = 'Check out this image here!' msg['From'] = EMAIL_ADDRESS msg['To'] = '*****@*****.**' msg.set_content('Image attached...') with open('pic.jpg', 'rb') as f: file_data = f.read() file_type = imghdr.what(f.name) file_name = f.name # print(file_type) 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)
from os import environ import smtplib import imghdr from email.message import EmailMessage email = environ.get('EMAIL_USER') password = environ.get('EMAIL_PASS') msg = EmailMessage() msg['Subject'] = "Meeting Report" msg['From'] = email msg['To'] = email msg.set_content('Need to know the full report on how the meeting actually went. Image Attached!') files = ['10.png', '328.png', '904.png'] for file in files: with open(file, 'rb') as f: file_data = f.read() file_type = imghdr.what(f.name) file_name = f.name # print(file_type) 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, 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 # Create a text/plain message msg = EmailMessage() msg.set_content(""" Hallo liebe Anna! Viele Grüße Gabi """) msg['Subject'] = "Mein Betreff" msg['To'] = "*****@*****.**" # Send the message via our own SMTP server. s = smtplib.SMTP('smtp.gmail.com') username = input("Username?") msg['From'] = username # bei GMX korrespondieren Username und E-Mail-Adresse password = input("Password?") s.starttls() s.login(username, password) s.send_message(msg) s.quit()
import smtplib from email.message import EmailMessage email = EmailMessage() email['from'] = 'Your lover' email['to'] = '*****@*****.**' email['subject'] = 'INTROduction' email.set_content( 'hello adarsh i just sent you this mail without logging into my account .STAY HOME STAY SAFE' ) with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp: smtp.ehlo() smtp.starttls() smtp.login('*****@*****.**', 'yashas2001') smtp.send_message(email) print('all good')
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'] = 'Umar Hegde' email['to'] = '<to email address > email['subject'] = 'Email Subject' email.set_content(html.substitute({'name': '-'}), 'html') with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp: smtp.ehlo() smtp.starttls() smtp.login('<your email address>', '<your password>') smtp.send_message(email) print('all good boss!')
def __init__(self, mailTo=False, subject=False, message=False): valid.validateInput(mailTo, subject, message) self.mail = EmailMessage() self.mail['Subject'] = subject self.mail['To'] = mailTo self.mail.set_content(message)
#!/usr/bin/env python3 from smtplib import SMTP from email.message import EmailMessage with open('employee_emails.txt', 'r') as emailFile: emails = emailFile.read().split('\n') message = '' message += 'Hi there,\nWe require you to immediately open this link and verify the information. ' message += 'Make it quick or you\'ll be in trouble!\n\n' message += 'http://10.10.14.120/' message += '\n\nRegards,\nSneakymailer CEO' for email in emails: msg = EmailMessage() msg.set_content(message) msg['Subject'] = 'Look at this immediately' msg['From'] = '*****@*****.**' msg['To'] = email print(f'Sending to: {email}', end='') with SMTP('sneakymailer.htb') as server: server.send_message(msg) print(' - message sent!')
# 메일 보내기: HTML 메일 전송하기 import smtplib from email.message import EmailMessage SMTP_SERVER = 'smtp.gmail.com' SMTP_PORT = 587 sender = '*****@*****.**' recipient = '*****@*****.**' password = '******' msg = EmailMessage() msg['Subject'] = "HTML 메시지 전송" msg['From'] = sender # 보내는 사람을 튜플로 지정 msg['To'] = ('*****@*****.**', '*****@*****.**') # HTML 메시지 작성하기 # content_id = 'my_image1' # add_alternative : 이 함수는 html로 보내고 싶은 내용을 추가할 수 있음 msg.add_alternative('''\ <html> <head></head> <body> <p>안녕하세요.</p> <p>순천향대학교 김대희입니다.</p> <p>아래 사이트 확인 부탁 드립니다.</p> <p> <a href=https://labs.sch.ac.kr/department/iot/m/> 순천향대학교 사물인터넷학과</a>
import re SMTP_SERVER = "smtp.gmail.com" SMTP_PORT = 465 def sendEmail(addr): reg = "^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$" if bool(re.match(reg, addr)): smtp.send_message(message) print("정상적으로 메일이 발송되었습니다.") else: print("유효한 이메일 주소가 아닙니다.") message = EmailMessage() message.set_content("수업중입니다.") message["Subject"] = "이것은 제목입니다." message["From"] = "###@gmail.com" message["To"] = "###@gmail.com" with open("codelion.png", "rb") as image: image_file = image.read() image_type = imghdr.what('codelion', image_file) message.add_attachment(image_file, maintype='image', subtype=image_type) smtp = smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT) smtp.login("###@gmail.com", "######") sendEmail("###gmailcom")