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 _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_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 create_message(self, *, subject: str = None, sender: Union[str, Address] = None, to: AddressListType = None, cc: AddressListType = None, bcc: AddressListType = None, charset: str = None, plain_body: str = None, html_body: str = None) -> EmailMessage: """ Create an :class:`~email.message.EmailMessage` using to be sent later using :meth:`deliver`. :param subject: subject line for the message :param sender: sender address displayed in the message (the From: header) :param to: primary recipient(s) (displayed in the message) :param cc: secondary recipient(s) (displayed in the message) :param bcc: secondary recipient(s) (**not** displayed in the message) :param charset: character encoding of the message :param plain_body: plaintext body :param html_body: HTML body """ assert check_argument_types() msg = EmailMessage() msg['Subject'] = subject or self.message_defaults.get('subject') sender = sender or self.message_defaults.get('sender') if sender: msg['From'] = sender to = to or self.message_defaults.get('to') if to: msg['To'] = to cc = cc or self.message_defaults.get('cc') if cc: msg['Cc'] = cc bcc = bcc or self.message_defaults.get('bcc') if bcc: msg['Bcc'] = bcc charset = charset or self.message_defaults.get('charset') if plain_body is not None and html_body is not None: msg.set_content(plain_body, charset=charset) msg.add_alternative(html_body, charset=charset, subtype='html') elif plain_body is not None: msg.set_content(plain_body, charset=charset) elif html_body is not None: msg.set_content(html_body, charset=charset, subtype='html') return 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 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 send(self): try: msg = EmailMessage() msg['Date'] = formatdate() msg['Subject'] = self.subject msg['From'] = Address('Alpha Geeks', *self.sender.split('@')) msg['To'] = tuple( Address('System Admin', *t.split('@')) for t in self.to ) msg.set_content(self.content) if self.html is not None: msg.add_alternative("""<html> <head><title>{title}</title> </head><body><pre>{body}</pre> </body></html> """.format( title=self.subject, body=self.html ), subtype='html') with SMTP(self.server) as con: con.login(self.user, self.passwd) con.send_message(msg) except Exception as e: sys.exit("mail failed: %s" % str(e))
def deliver_email(self, id, rx, msgbody, status_recorder): ''' gateway gives us plenty of info, what we want out of it is: date_created, error_code, error_message, sid, status we'll parse the error_code and error_message and return them in sendStatus ''' urgheaders = [ ('Priority','Urgent'), ('X-Priority','1 (Highest)'), ('Importance','High'), ('X-MMS-Priority','Urgent') ] emailheaders = [ ('To', 'SMVFD'), ('From', 'DispatchBuddy <*****@*****.**>'), ('Subject', 'Fire Dispatch: {address}'.format(address=self.evdict['address'])), ] send_results = [] now = datetime.datetime.utcnow() msg = EmailMessage() for h,v in emailheaders: msg[h]=v msg.set_content('This is an HTML only email') magnify_icon_cid = make_msgid() medias = [] fdict = {'meta_icons':'', 'magnify_icon_cid':magnify_icon_cid[1:-1]} self.logger.debug('ADD MMS urls, search for keys in: {}'.format(self.evdict['nature'])) for rk in sorted(media_urls): if re.search(rk, self.evdict['nature']) or re.search(rk, self.evdict['notes']): self.logger.debug('found key: {}'.format(rk)) media = media_urls.get(rk) if not media: media = media_urls['UNKNOWN'] media = 'https://southmeriden-vfd.org/images/dispatchbuddy/icon-'+media medias.append(media) medias = set(medias) self.logger.debug('media urls: {}'.format(medias)) meta_icons_t = '' if medias: meta_icons_t = '' for url in medias: meta_icons_t += '<img class="meta_icons" src="{url}">'.format(url=url) fdict.update({'meta_icons':meta_icons_t}) for kw in ('meta_icons', 'magnify_icon_cid'): msgbody = msgbody.replace('{{'+kw+'}}','{'+kw+'}') msgbody = msgbody.format(**fdict) # now replace all the {{ and }} msgbody = msgbody.replace('{{','{').replace('}}','}') msg.add_alternative(msgbody, subtype='html') with open('/var/bluelabs/DispatchBuddy/images/magnify.gif', 'rb') as img: msg.get_payload()[1].add_related(img.read(), 'image', 'gif', cid=magnify_icon_cid) ''' related = MIMEMultipart(_subtype='related') innerhtml = MIMEText(msgbody, _subtype='html') related.attach(innerhtml) related.attach(icon_magnify_gif) ''' for h,v in urgheaders: msg[h]=v bcc = [r.address for r in rx] ''' medias = [] if self.mediatype == 'mms': for rk in sorted(media_urls): if re.search(rk, self.evdict['nature']) or re.search(rk, self.evdict['notes']): media = media_urls.get(rk) if not media: media = media_urls['UNKNOWN'] media = 'https://southmeriden-vfd.org/images/dispatchbuddy/'+media args['media_url'] = medias print('args list: {}'.format(args)) ''' host = self.config.get('SMTP', 'host') ehlo = self.config.get('SMTP', 'ehlo') user = self.config.get('SMTP', 'user') pass_ = self.config.get('SMTP', 'pass') from_ = self.config.get('SMTP', 'from') try: s = smtplib.SMTP(host=host, port='25') #s.set_debuglevel(1) s.starttls() s.ehlo(ehlo) s.login(user, pass_) # keep_results is my own patch to smtplib try: sresponse = s.sendmail(from_, bcc, msg.as_string(), mail_options=['SMTPUTF8'], keep_results=True) except TypeError: self.logger.critical('Need to patch smtplib for keep_results again; https://bugs.python.org/issue29539') sresponse = s.sendmail(from_, bcc, msg.as_string(), mail_options=['SMTPUTF8']) qresponse = s.quit() self.logger.debug('server sresponse: {}'.format(sresponse)) self.logger.debug('server qresponse: {}'.format(qresponse)) for r in bcc: code,status = sresponse[r] status = status.decode().split() id = status[4] status = status[2] try: status_recorder(recipient=r, delivery_id=id, status=status) except Exception as e: self.logger.warning('unable to relay status elements to DB recorder: {}'.format(e)) status_recorder(recipient=r, delivery_id=id, status='failed', reason=str(e), completed=True) except Exception as e: self.logger.warning('Failed to send message to recipients: {}'.format(e)) for r in bcc: try: status_recorder(recipient=r, delivery_id='smtp failure', status='failed', reason=str(e), completed=True) except Exception as ee: self.logger.warning('status recording error: {}'.format(ee))
row_mod = {} for j, a in row.items(): j = j.lower().replace(" ", "_") row_mod[j] = a imgs_lcl = imgs.copy() for plugin_name, plugin in plugins.items(): row_mod, imgs_lcl = plugin.process_row(row_mod, imgs_lcl) text = text_tmplt.substitute(row_mod) html = html_tmplt.substitute(row_mod) email = EmailMessage() email["Subject"] = args.subject email["From"] = args.sent_from email["To"] = receiver_email email.set_content(text) email.add_alternative(html, subtype="html") for img in imgs_lcl: email.get_payload()[1].add_related(img["img"], maintype=img["maintype"], subtype=img["subtype"], cid=img["tag"]) server.sendmail(sender_email, receiver_email, email.as_string()) if not args.no_debug: th.join()
msg['Bcc'] = BCC_ADDR msg.add_header('reply-to', REPLY_TO_ADDRESS) msg.set_content("""\ See my message in attach""") # Add the html version. This converts the message into a multipart/alternative # container, with the original text message as the first part and the new html # message as the second part. meme_cid = make_msgid() msg.add_alternative("""\ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=ISO-8859-15"> </head> Keep the strong momentum! <body bgcolor="#ffffff" text="#000000"> <img src="cid:{meme_cid}" \> </body> </html> """.format(meme_cid=meme_cid[1:-1]), subtype='html') # note that we needed to peel the <> off the msgid for use in the html. # Now add the related image to the html part. with open(IMG, 'rb') as img: msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg', cid=meme_cid) # Send the message via local SMTP server. with smtplib.SMTP(SMTP_SERVER, 25) as s: s.send_message(msg)
def test_text_html_attachment() -> None: # Adapted from <https://docs.python.org/3/library/email.examples.html> msg = EmailMessage() msg["Subject"] = "Ayons asperges pour le déjeuner" msg["From"] = Address("Pepé Le Pew", "pepe", "example.com") msg["To"] = ( Address("Penelope Pussycat", "penelope", "example.com"), Address("Fabrette Pussycat", "fabrette", "example.com"), ) TEXT = ( "Salut!\n" "\n" "Cela ressemble à un excellent recipie[1] déjeuner.\n" "\n" "[1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718\n" "\n" "--Pepé\n") msg.set_content(TEXT) asparagus_cid = make_msgid() HTML = ("<html>\n" " <head></head>\n" " <body>\n" " <p>Salut!</p>\n" " <p>Cela ressemble à un excellent\n" ' <a href="http://www.yummly.com/recipe/Roasted-Asparagus-' 'Epicurious-203718">\n' " recipie\n" " </a> déjeuner.\n" " </p>\n" f' <img src="cid:{asparagus_cid[1:-1]}" />\n' " </body>\n" "</html>\n") msg.add_alternative(HTML, subtype="html") IMG = b"\1\2\3\4\5" msg.get_payload()[1].add_related(IMG, "image", "png", cid=asparagus_cid) DICT: MessageDict = { "unixfrom": None, "headers": { "subject": "Ayons asperges pour le déjeuner", "from": [ { "display_name": "Pepé Le Pew", "address": "*****@*****.**", }, ], "to": [ { "display_name": "Penelope Pussycat", "address": "*****@*****.**", }, { "display_name": "Fabrette Pussycat", "address": "*****@*****.**", }, ], "content-type": { "content_type": "multipart/alternative", "params": {}, }, }, "preamble": None, "content": [ { "unixfrom": None, "headers": { "content-type": { "content_type": "text/plain", "params": {}, }, }, "preamble": None, "content": TEXT, "epilogue": None, }, { "unixfrom": None, "headers": { "content-type": { "content_type": "multipart/related", "params": {}, }, }, "preamble": None, "content": [ { "unixfrom": None, "headers": { "content-type": { "content_type": "text/html", "params": {}, }, }, "preamble": None, "content": HTML, "epilogue": None, }, { "unixfrom": None, "headers": { "content-type": { "content_type": "image/png", "params": {}, }, "content-disposition": { "disposition": "inline", "params": {}, }, "content-id": [asparagus_cid], }, "preamble": None, "content": IMG, "epilogue": None, }, ], "epilogue": None, }, ], "epilogue": None, } assert email2dict(msg) == DICT DICT_ALL = deepcopy(DICT) DICT_ALL["headers"]["mime-version"] = "1.0" DICT_ALL["content"][0]["headers"]["content-transfer-encoding"] = "8bit" DICT_ALL["content"][0]["headers"]["content-type"]["params"][ "charset"] = "utf-8" DICT_ALL["content"][1]["headers"]["mime-version"] = "1.0" DICT_ALL["content"][1]["content"][0]["headers"][ "content-transfer-encoding"] = "quoted-printable" DICT_ALL["content"][1]["content"][0]["headers"]["content-type"]["params"][ "charset"] = "utf-8" DICT_ALL["content"][1]["content"][1]["headers"]["mime-version"] = "1.0" DICT_ALL["content"][1]["content"][1]["headers"][ "content-transfer-encoding"] = "base64" assert email2dict(msg, include_all=True) == DICT_ALL
def sendEmail(self, args, f_type): """ Sends email :param args: :param f_type: :return: """ try: recipient = self.core.resolve_arg(args[0], f_type) except IndexError: raise BBotException({ 'code': 250, 'function': 'sendEmail', 'arg': 0, 'message': 'Recipient address is missing.' }) try: sender = self.core.resolve_arg(args[1], f_type) except IndexError: raise BBotException({ 'code': 251, 'function': 'sendEmail', 'arg': 1, 'message': 'Sender address is missing.' }) if type(recipient) is not str: raise BBotException({ 'code': 251, 'function': 'sendEmail', 'arg': 0, 'message': 'Recipient has to be string.' }) try: subject = self.core.resolve_arg(args[2], f_type) except IndexError: raise BBotException({ 'code': 252, 'function': 'sendEmail', 'arg': 2, 'message': 'Subject is missing.' }) if type(subject) is not str: raise BBotException({ 'code': 251, 'function': 'sendEmail', 'arg': 2, 'message': 'Subject has to be string.' }) try: body = self.core.resolve_arg(args[3], f_type) except IndexError: raise BBotException({ 'code': 253, 'function': 'sendEmail', 'arg': 3, 'message': 'Email body is missing.' }) smtp_config = self.core.dotbot['smtp'] msg = EmailMessage() msg['Subject'] = subject msg['From'] = sender msg['To'] = recipient body = body.replace('\n', '<br />') msg.set_content( "Please see this email with an html compatible email client\n") msg.add_alternative(f"""\ <html> <head></head> <body> {body} </body> </html> """, subtype='html') self.logger.debug( f"Sending email through {smtp_config['server_host']}:{smtp_config['server_port']} to {recipient}" ) smtp = smtplib.SMTP(smtp_config['server_host'], smtp_config['server_port']) smtp.set_debuglevel(1) if smtp_config.get('server_username', "") and smtp_config.get( 'serer_password', ""): smtp.login(smtp_config['server_username'], smtp_config['server_password']) smtp.send_message(msg) smtp.quit()
contacts = ['*****@*****.**', '*****@*****.**', '*****@*****.**'] msg = EmailMessage() msg['Subject'] = 'This your dream car' msg['From'] = EMAIL_ADDRESS msg['To'] = ', '.join(contacts) msg.set_content ('This....') #here we are using the separate html file instead of using the tripple quotes with open('email.html', 'rb') as f: file_data = f.read() file_name = f.name file_string = file_data.decode(encoding='UTF-8') msg.add_alternative(file_string, subtype='html') ''' - How we attach images to the email - If images are several we can use a for loop with open('example.jpg', '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) ''' '''
import os import smtplib import imghdr from email.message import EmailMessage EMAIL_ADDRESS = "" EMAIL_PASSWORD = "" contacts = ['*****@*****.**'] msg = EmailMessage() msg['Subject'] = 'Check out Bronx as a puppy!' msg['From'] = EMAIL_ADDRESS msg['To'] = '*****@*****.**' msg.set_content('This is a plain text email') msg.add_alternative("""\ <!DOCTYPE html> <html> <body> <h1 style="color:SlateGray;">This is an HTML Email!</h1> </body> </html> """, subtype='html') with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD) smtp.send_message(msg)
def _mail_recipient(recipient_name, recipient_email, sender_name, sender_url, subject, body, body_html=None, headers=None, attachments=None): if not headers: headers = {} if not attachments: attachments = [] mail_from = config.get_value('smtp.mail_from') reply_to = config.get_value('smtp.reply_to') msg = EmailMessage() msg.set_content(body, cte='base64') if body_html: msg.add_alternative(body_html, subtype='html', cte='base64') for k, v in headers.items(): if k in msg.keys(): msg.replace_header(k, v) else: msg.add_header(k, v) msg['Subject'] = subject msg['From'] = _("%s <%s>") % (sender_name, mail_from) msg['To'] = u"%s <%s>" % (recipient_name, recipient_email) msg['Date'] = utils.formatdate(time()) msg['X-Mailer'] = "CKAN %s" % ckan.__version__ if reply_to and reply_to != '': msg['Reply-to'] = reply_to for attachment in attachments: if len(attachment) == 3: name, _file, media_type = attachment else: name, _file = attachment media_type = None if not media_type: media_type, encoding = mimetypes.guess_type(name) if media_type: main_type, sub_type = media_type.split('/') else: main_type = sub_type = None msg.add_attachment(_file.read(), filename=name, maintype=main_type, subtype=sub_type) # Send the email using Python's smtplib. smtp_server = config.get_value('smtp.server') smtp_starttls = config.get_value('smtp.starttls') smtp_user = config.get_value('smtp.user') smtp_password = config.get_value('smtp.password') try: smtp_connection = smtplib.SMTP(smtp_server) except (socket.error, smtplib.SMTPConnectError) as e: log.exception(e) raise MailerException( 'SMTP server could not be connected to: "%s" %s' % (smtp_server, e)) try: # Identify ourselves and prompt the server for supported features. smtp_connection.ehlo() # If 'smtp.starttls' is on in CKAN config, try to put the SMTP # connection into TLS mode. if smtp_starttls: if smtp_connection.has_extn('STARTTLS'): smtp_connection.starttls() # Re-identify ourselves over TLS connection. smtp_connection.ehlo() else: raise MailerException("SMTP server does not support STARTTLS") # If 'smtp.user' is in CKAN config, try to login to SMTP server. if smtp_user: assert smtp_password, ("If smtp.user is configured then " "smtp.password must be configured as well.") smtp_connection.login(smtp_user, smtp_password) smtp_connection.sendmail(mail_from, [recipient_email], msg.as_string()) log.info("Sent email to {0}".format(recipient_email)) except smtplib.SMTPException as e: msg = '%r' % e log.exception(msg) raise MailerException(msg) finally: smtp_connection.quit()
data_combine = CA_data.append(data_today).reset_index(drop=True) data_combine.to_csv('/Users/mengn/Covid_CA.csv', index=False) plot = data_combine.plot(x='Date', y='New_Cases', color='#e5ae38', label='Canada') fig = plot.get_figure() fig.savefig("/Users/mengn/Covid_19.jpg") msg = EmailMessage() msg['Subject'] = 'latest Covid-19 Update' msg['From'] = '*****@*****.**' msg['To'] = ['*****@*****.**'] #msg.set_content(c) msg.add_alternative(c, subtype='html') with open('/Users/mengn/Covid_19.jpg', '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) with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.login('*****@*****.**', 'password') smtp.send_message(msg)
attachment = one_record[7] attachment_name = one_record[8] #print (email,subject,content) print(email) with SMTP(my_pass.smtp_host) as smtp: smtp.starttls() smtp.login(my_pass.smtp_email, my_pass.smtp_pass) try: #SMTP.sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=()) #smtp.sendmail('',email,content) msg = EmailMessage() msg['Subject'] = subject msg['To'] = email msg['From'] = '*****@*****.**' msg.add_alternative(content, subtype='html') if (attachment): msg.add_attachment(attachment, maintype='application', subtype='octet-stream', filename=attachment_name) smtp.send_message(msg) except Exception as my_ex: logging.critical('Error in sending email') logging.debug(my_ex) #fail of success, nomore second attempt sql_update = 'update email set sent=1 where id=%s' data_tuple_update = (email_db_id, ) cur_update = run_query(conn, sql_update, data_tuple_update) close_cursor(cur_update)
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 message_id: :param references: :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(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
async def send_email( self, e_from: Union[str, SesRecipient], subject: str, to: Optional[List[Union[str, SesRecipient]]] = None, text_body: str = '', html_body: Optional[str] = None, *, cc: Optional[List[Union[str, SesRecipient]]] = None, bcc: Optional[List[Union[str, SesRecipient]]] = None, attachments: Optional[List[SesAttachment]] = None, unsubscribe_link: Optional[str] = None, configuration_set: Optional[str] = None, message_tags: Optional[Dict[str, Any]] = None, smtp_headers: Optional[Dict[str, str]] = None, ) -> str: email_msg = EmailMessage() email_msg['Subject'] = subject e_from_recipient = as_recipient(e_from) email_msg['From'] = e_from_recipient.display() to_r: List[SesRecipient] = [] cc_r: List[SesRecipient] = [] bcc_r: List[SesRecipient] = [] if to: to_r = [as_recipient(r) for r in to] email_msg['To'] = ', '.join(r.display() for r in to_r) if cc: cc_r = [as_recipient(r) for r in cc] email_msg['Cc'] = ', '.join(r.display() for r in cc_r) if bcc: bcc_r = [as_recipient(r) for r in bcc] email_msg['Bcc'] = ', '.join(r.display() for r in bcc_r) if unsubscribe_link: email_msg['List-Unsubscribe'] = f'<{unsubscribe_link}>' if configuration_set: email_msg['X-SES-CONFIGURATION-SET'] = configuration_set if message_tags: email_msg['X-SES-MESSAGE-TAGS'] = ', '.join(f'{k}={v}' for k, v in message_tags.items()) if smtp_headers: for name, value in smtp_headers.items(): email_msg[name] = value email_msg.set_content(text_body) if html_body: email_msg.add_alternative(html_body, subtype='html') total_size = 0 for attachment in attachments or []: attachment_msg, size = await prepare_attachment(attachment) total_size += size if total_size > max_total_size: raise ValueError(f'attachment size {total_size} greater than 10MB') if email_msg.get_content_maintype() == 'text': email_msg.make_mixed() email_msg.attach(attachment_msg) return await self.send_raw_email(e_from_recipient.email, email_msg, to=to_r, cc=cc_r, bcc=bcc_r)
def send_html_mail(template, to_email, data=None, subject=None): ''' Send an email with HTML content # Input - template : (str) name of the template to look for in templates/ directory - to_email : (str) receiver's email - (optional) data : (dict str:str ) dictionnary with the string values to insert into the template variables. - (optional) subject : (str) the subject for the email. Can contain variable to be filled with the data dict. If None, will look for subject.txt in templates/TEMPLATE ''' # LOADING DATA if subject is None: assert path.isfile( path.join(CURDIR, "templates", template, "subject.txt") ), "Please provide a subject file or specifiy the subject in the arguments." with open(path.join(CURDIR, "templates", template, "subject.txt"), 'r') as f: subject = f.readline() data = data or {} # SETTING MAIL DETAILS me = Address(EMAIL) msg = EmailMessage() msg['Subject'] = subject msg['From'] = [ Address(display_name=DISPLAY_NAME, username=USERNAME, domain=DOMAIN) ] msg['To'] = [Address(to_email)] msg["X-Entity-Ref-ID"] = "".join([str(randint(0, 10)) for i in range(20)]) # SETTING THE PLAIN TEXT CONTENT if path.isfile( path.join(CURDIR, "templates", template, "plain_message.txt")): with open( path.join(CURDIR, "templates", template, "plain_message.txt"), 'r') as f: plain_text = "\n".join(f.readlines()) msg.set_content(plain_text) # SETTING THE HTML RESPONSE assert path.isfile( path.join(CURDIR, "templates", template, "body.html")), "Could not find body.html in {}".format( path.join(CURDIR, "templates", template)) with open(path.join(CURDIR, "templates", template, "body.html"), 'r') as f: html_content = " ".join(f.readlines()) html_template = Template(html_content) ## Replacing variables inside the html ## Configuring images cids = {} if path.isdir(path.join(CURDIR, "templates", template, "images")): for image in listdir(path.join(CURDIR, "templates", template, "images")): cids[image] = make_msgid()[1:-1] print("Rendering with", cids, data) html_rendered = html_template.render( **{image.split(".")[0]: cid for image, cid in cids.items()}, **data) msg.add_alternative(html_rendered, subtype='html') ### attaching images for image, cid in cids.items(): image_path = path.join(CURDIR, "templates", template, "images", image) maintype, subtype = mimetypes.guess_type(image_path)[0].split('/', 1) msg.get_payload()[1].add_related( # image/png Path(image_path).read_bytes(), maintype, subtype, cid="<{}>".format(cid)) ## Sending mail context = ssl.create_default_context() try: with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server: server.login(EMAIL, PASSWORD) server.sendmail(EMAIL, to_email, msg.as_string()) except Exception as err: print_clean_stack(err) exit(1)
contacts = ['*****@*****.**'] msg = EmailMessage() msg['Subject'] = 'Hello from python' msg['From'] = EMAIL_ADDRESS msg['To'] = contacts msg.set_content('This is a plain text email') m = "hellooooooo" msg.set_content('normal message as a alternative of html') msg.add_alternative("""\ <!DOCTYPE html> <html> <body> <img src="https://picsum.photos/500" width=100%> </body> </html> """, subtype='html') ''' <!DOCTYPE html> <html> <style> .parent{ position:relative; } img{ padding:0; }
def form_mime_alert_message(self,subject = None,body = None,recipient = None,images = None,attachments = None): if subject is not None: self.subject = subject if body is not None: self.body = body if recipient is not None: self.recipient = recipient self.images = images self.attachments = attachments if self.images is None: nImg = 0 else: nImg = len(self.images) if self.attachments is None: nAttch = 0 else: nAttch = len(self.attachments) msg = EmailMessage() # generic email headers msg['Subject'] = self.subject msg['From'] = '<' + self.sender + '>' msg['To'] = '<' + self.recipient + '>' # set the plain text body msg.set_content(self.body) # alternate html msgTxt = self.body msgTxt = msgTxt.replace("\n","<br>") image_cids = [] for i in range(nImg): cid = make_msgid() image_cids.append(cid) cid = cid[1:-1] # remove < > msgTxt = msgTxt + '<br><img src="cid:' + cid + '"><br>' # add image tag to html msg.add_alternative(msgTxt,subtype='html') # now open the images and attach to the email for i in range(nImg): with open(self.images[i], 'rb') as img: # know the Content-Type of the image maintype, subtype = mimetypes.guess_type(img.name)[0].split('/') # attach it msg.get_payload()[1].add_related(img.read(), maintype=maintype, subtype=subtype, cid=image_cids[i]) # end for # attach additional attachments for i in range(nAttch): with open(self.attachments[i], 'rb') as fp: # get content type ctype, encoding = mimetypes.guess_type(fp.name) if ctype is None or encoding is not None: # unknown or compressed ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) # attach it msg.get_payload()[1].add_related(fp.read(), maintype=maintype, subtype=subtype, filename=os.path.basename(fp.name)) # end for self.full_email_text = msg.as_string()
import smtplib import os import imghdr from email.message import EmailMessage from collections import namedtuple senderinfo = namedtuple('senderinfo', ('email', 'password')) sender = senderinfo(os.environ.get('PYEMAIL'), os.environ.get('PYPASSWORD')) mail = EmailMessage() mail['Subject'] = 'This is subject' mail['From'] = f'Sender Name <{sender.email}>' mail['To'] = ['', '', ''] # Put the emails here as much as you wish. Seperate them with comma. mail.add_alternative("""\ This mail sent by <b>{0}</b> """.format(sender.email), subtype='html') # Mail content using html imgfiles = ['./images/img1.jpg', './images/img2.png'] # image files if you wish to add for imgfile in imgfiles: with open(imgfile, 'rb') as file: file_data = file.read() file_type = imghdr.what(file.name) file_name = file.name.split('/')[-1] mail.add_attachment(file_data, maintype='image', subtype=file_type, filename=file_name) pdfiles = ['./pdfs/pdf1.pdf', './pdfs/pdf2.pdf'] # pdf files if you wish to add for pdfile in pdfiles: with open(pdfile, 'rb') as f: file_data = f.read() file_name = f.name.split('/')[-1] mail.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name)
import smtplib from email.message import EmailMessage import getpass password = getpass.getpass('what`s your password? : ') email_list = ['*****@*****.**', '*****@*****.**'] msg = EmailMessage() msg['Subject'] = "안녕 난 거니야" msg['From'] = "*****@*****.**" msg['To'] = "*****@*****.**" #msg.set_content('') msg.add_alternative(''' <h1>안녕하세요.</h1> <p>저는 송건희입니다.</p> ''', subtype="html") #string을 여러 줄 거쳐서 보낼 때 ``` 사용함. subtype="html" : html 형식 사용. #h1 : 글자 크고 진하게 #p : smtp_url = 'smtp.naver.com' smtp_port = 465 s = smtplib.SMTP_SSL(smtp_url, smtp_port) #smptlib.SMPT_SLL()은 보안 연결을 위해 하는 작업임. s.login("*****@*****.**", password) #s.login(id, pw) s.send_message(msg)
import smtplib from email.message import EmailMessage from email.utils import make_msgid msg = EmailMessage() asparagus_cid = make_msgid() msg.set_content('This is a text message') msg.add_alternative("""\ <html> <head></head> <body> <p>Hello</p> <p> Here is an example of sending attachments in email using Python. </p> <img src="cid:{asparagus_cid}" /> </body> </html> """.format(asparagus_cid=asparagus_cid[1:-1]), subtype='html') with open("sample.jpg", 'rb') as img: msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg', cid=asparagus_cid) with open("sample.pdf", 'rb') as fp: pdf_data = fp.read() ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) msg.add_attachment(pdf_data, maintype=maintype, subtype=subtype, filename='sample.pdf')
def run( self, subject: str = None, msg: str = None, email_to: str = None, email_from: str = None, smtp_server: str = None, smtp_port: int = None, smtp_type: str = None, msg_plain: str = None, email_to_cc: str = None, email_to_bcc: str = None, ) -> None: """ Run method which sends an email. Args: - subject (str, optional): the subject of the email; defaults to the one provided at initialization - msg (str, optional): the contents of the email; defaults to the one provided at initialization - email_to (str, optional): the destination email address to send the message to; defaults to the one provided at initialization - email_from (str, optional): the email address to send from; defaults to the one provided at initialization - smtp_server (str, optional): the hostname of the SMTP server; defaults to the one provided at initialization - smtp_port (int, optional): the port number of the SMTP server; defaults to the one provided at initialization - smtp_type (str, optional): either SSL or STARTTLS; defaults to the one provided at initialization - msg_plain (str, optional): the contents of the email, added as plain text can be used in combination of msg; defaults to the one provided at initialization - email_to_cc (str, optional): additional email address to send the message to as cc; defaults to the one provided at initialization - email_to_bcc (str, optional): additional email address to send the message to as bcc; defaults to the one provided at initialization Returns: - None """ username = cast(str, Secret("EMAIL_USERNAME").get()) password = cast(str, Secret("EMAIL_PASSWORD").get()) message = EmailMessage() message["Subject"] = subject message["From"] = email_from message["To"] = email_to if email_to_cc: message["Cc"] = email_to_cc if email_to_bcc: message["Bcc"] = email_to_bcc # https://docs.python.org/3/library/email.examples.html # If present, first set the plain content of the email. After which the html version is # added. This converts the message into a multipart/alternative container, with the # original text message as the first part and the new html message as the second part. if msg_plain: message.set_content(msg_plain, subtype="plain") if msg: message.add_alternative(msg, subtype="html") context = ssl.create_default_context() if smtp_type == "SSL": server = smtplib.SMTP_SSL(smtp_server, smtp_port, context=context) elif smtp_type == "STARTTLS": server = smtplib.SMTP(smtp_server, smtp_port) server.starttls(context=context) else: raise ValueError( f"{smtp_type} is an unsupported value for smtp_type.") server.login(username, password) try: server.send_message(message) finally: server.quit()
def register_school(request): msg = EmailMessage() if request.method == "POST": form = KidsSchoolRegister(request.POST) if form.is_valid(): kids_email = form.cleaned_data.get('email') kids_school = form.cleaned_data.get('school') if User.objects.filter(email=kids_email).exists(): messages.info( request, f"Sorry,a user with the same email already exists") else: form.save() Student.objects.create(student_email=kids_email) msg["Subject"] = "Thank you for joining our summer tutoring program." msg["From"] = settings.EMAIL_HOST_USER msg["To"] = kids_email msg.set_content( "We are glad you have decided to join us in this studies,so you know it's going to be more fun than you expected,stay blessed and see you in class." ) hml = f""" <!Doctype html> <html> <body> <h1 style='font-style:italic;'>Thank you for joining our summer tutoring program.</h1> <p style='color:SlateGray;'> We are glad you have decided to join us in this studies,so you know it's going to be more fun than you expected,stay blessed and see you in class.</p> <p style='color:SlateGray;'>ORgeonofstars</p> </body> </html> </html> """ msg.add_alternative(hml, subtype='html') with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD) smtp.send_message(msg) messages.success( request, f"Thank you for joining our summer tutoring program.") return redirect('school_login') # to organization email msg["Subject"] = "A new Kid just joined the gradeschool summer tutoring program" msg["From"] = settings.EMAIL_HOST_USER msg["To"] = settings.EMAIL_HOST_USER msg.set_content( "Got a new kid for the summer tutoring program.") hml = f""" <!Doctype html> <html> <body> <h1 style='font-style:italic;'>A new Kid just joined the gradeschool summer tutoring program</h1> <p style='color:SlateGray;'> Got a new kid for the summer tutoring program.</p> <p style='color:SlateGray;'>ORgeonofstars</p> </body> </html> </html> """ msg.add_alternative(hml, subtype='html') with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD) smtp.send_message(msg) else: messages.info(request, f"Something went wrong") else: form = KidsSchoolRegister() context = {"form": form} return render(request, "summerschool/schoolregister.html", context)
""") # Add the html version. This converts the message into a multipart/alternative # container, with the original text message as the first part and the new html # message as the second part. asparagus_cid = make_msgid() msg.add_alternative("""\ <html> <head></head> <body> <p>Greetings!<\p> <p>Merry Chrismass chicken recipe <a href="http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718> recipie </a> regards. </p> <img src="cid:{asparagus_cid}" \> </body> </html> """.format(asparagus_cid=asparagus_cid[1:-1]), subtype='html') # note that we needed to peel the <> off the msgid for use in the html. # Now add the related image to the html part. with open("roasted-asparagus.jpg", 'rb') as img: msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg', cid=asparagus_cid)
[1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718 --Pepé """) # Add the html version. This converts the message into a multipart/alternative # container, with the original text message as the first part and the new html # message as the second part. asparagus_cid = make_msgid() msg.add_alternative("""\ <html> <head></head> <body> <p>Salut!<\p> <p>Cela ressemble à un excellent <a href="http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718> recipie </a> déjeuner. </p> <img src="cid:{asparagus_cid}" \> </body> </html> """.format(asparagus_cid=asparagus_cid[1:-1]), subtype='html') # note that we needed to peel the <> off the msgid for use in the html. # Now add the related image to the html part. with open("roasted-asparagus.jpg", 'rb') as img: msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg', cid=asparagus_cid) # Make a local copy of what we are going to send. with open('outgoing.msg', 'wb') as f:
msg.add_alternative("""\ <html> <head></head> <body> <p>Bonjour,</p> <p>Pour accéder au site de démonstration LabResult, vous pouvez utiliser les identifiants suivant:</p> <ul> <li> patient : <ul> <li> identifiant : patient</li> <li> mot de passe : password</li> </ul> </li> <br> <li> médecin : <ul> <li> identifiant : docteur</li> <li> mot de passe : password</li> </ul> </li> <br> <li> biologiste : <ul> <li> identifiant : biologiste</li> <li> mot de passe : password</li> </ul> </li> </ul> LabResult<br> Tel : 07 82 42 32 12 <br> <img src="cid:{logo_cid}" \> </body> </html> """.format(logo_cid=logo_cid[1:-1]), subtype='html')
# Reading File file = pd.ExcelFile(excelFile, engine='openpyxl') # Email Setup s = smtplib.SMTP("smtp.gmail.com", 587) s.starttls() # Traffic encryption s.login(emailID, pwd) # SMTP Login count = 0 for sheet in file.sheet_names: print("\n\n<-- New Sheet -->\n") df1 = file.parse(sheet) for i in range(len(df1['EMAIL'])): with open(htmlfile_loc, 'r', encoding='utf8') as file: html_Content = str(file.read()) msg = EmailMessage() msg['Subject'] = subject msg['From'] = emailID msg['To'] = df1['EMAIL'][i] msg.add_alternative(html_Content, subtype="html") s.send_message(msg) count += 1 print(">>> ", df1['SRNO'][i], ": ", df1['EMAIL'][i], " : Sent") if (count % 60 == 0): print("\n\n <<>> Server CoolDown for 60 seconds <<>>\n\n") time.sleep(10) s.quit() print("\n\n <<:>> All Emails Sent <<:>>\n\n")
contacts = ['*****@*****.**', '*****@*****.**'] msg = EmailMessage() msg['Subject'] = 'Forgot Password' msg['From'] = EMAIL_ADDRESS msg['To'] = '*****@*****.**', '*****@*****.**' msg.set_content('This is a plain text email') msg.add_alternative("""\ <!DOCTYPE html> <html> <p>Hello {{username}},</p> <p>You or someone else has requested that a new password be generated for your account. If you made this request, then please click this link: <a href={{link}}><strong>reset password</strong></a>. If you did not make this request, then you can simply ignore this email.</p> <p>Best,</p> <p>Harrison</p> <p>[email protected]</p> </html> """, subtype='html') @app.route('/') def index(): return "It is working" # user register @app.route('/register', methods=['POST']) def register():
elif winner_or_winners == "winners": simple_explanation = f"\nПриложено изпращам печелившите ви за тази седмица." \ f"\nМоля да проверите дали трансакциите им са валидни и да ни върнете потвърждение." html_explanation = f"<p>Приложено изпращам печелившите ви за тази седмица.</p>" \ f"<p>Моля да проверите дали трансакциите им са валидни и да ни върнете потвърждение.</p>" message.set_content( f"Здравей, {name},{simple_explanation}\nПоздрави,\nБорис") message.add_alternative(f"""\ <!DOCTYPE html> <html lang="en"> <head> </head> <body> <p>Здравей, {name},</p> {html_explanation} <p>Поздрави,</p> <p>Борис</p> </body> </html> """, subtype="html") os.chdir(folder) with open(file.name, "rb") as f: file_data = f.read() file_name = f.name message.add_attachment(file_data, maintype="application",
def make_email_message( from_, to=None, cc=None, bcc=None, subject=None, text=None, html=None, attachments=None, attachment_data=None, # If replying to another message reply_to_message_id=None, reply_to_message_references=None, reply_to_html=None, raise_for_no_recipients=True, ): text = text or '' to = _ensure_multiple(to) cc = _ensure_multiple(cc) bcc = _ensure_multiple(bcc) message = EmailMessage() message['X-Mailer'] = f'Kanmail v{get_version()}' message['Date'] = formatdate() message['From'] = _make_address(from_) if raise_for_no_recipients and not any((to, cc, bcc)): raise ValueError('No recipients defined!') message['To'] = tuple(_make_address(a) for a in to) if cc: message['Cc'] = tuple(_make_address(a) for a in cc) if bcc: message['Bcc'] = tuple(_make_address(a) for a in bcc) if subject: message['Subject'] = subject if reply_to_message_id: message['In-Reply-To'] = reply_to_message_id references = reply_to_message_references or [] references.append(reply_to_message_id) message['References'] = ' '.join(references) # Attach the text part (simples!) message.set_content(text) # Make/attach the HTML part, including any quote if not html: html = markdownify(text) if reply_to_html: html = f'{html}<blockquote>{reply_to_html}</blockquote>' message.add_alternative(html, subtype='html') # Handle attached files if attachments: attachment_data = attachment_data or {} for attachment in attachments: mimetype = guess_type(attachment)[0] maintype, subtype = mimetype.split('/') data = attachment_data.get(attachment) if not data: raise Exception( f'Missing data in request for attachment: {attachment}') data = b64decode(data) message.add_attachment( data, maintype=maintype, subtype=subtype, filename=path.basename(attachment), ) return message
def dailyemailnews(): EMAIL_USERFASTMAIL = os.environ.get('EMAIL_USERFASTMAIL') EMAIL_PASSWORDFASTMAIL = os.environ.get('EMAIL_PASSWORDFASTMAIL') users = User.query.filter_by(position="Normal").all() for user in users: form = DailyNewsForm() image_url = form.image_url.data title = form.title.data description = form.description.data link = form.link.data uniquelink = routes.createphish_token(user) msg = EmailMessage() msg['Subject'] = 'Daily Email - GamiSE' msg['From'] = 'GamiSE <*****@*****.**>' msg['To'] = user.email msg.add_alternative( """\ <!DOCTYPE html> <style> a{ text-decoration:none; } </style> <head> </head> <table lang="en" role="presentation" aria-hidden="true" border="0" style="width: 100%;background-color: #ffffff;padding: 0px" align="center"> <tbody> <tr> <td align="center" style="padding: 0px"> <table border="0" align="center" style="padding: 0px"> <tbody> <tr> <td width="12" style="padding: 0px"> </td> <td style="padding: 0px"> <table border="0" style="padding: 0px;width: 650px"> <tbody> <tr> <td height="12" style="padding: 0px"></td> </tr> <tr> <td style="text-decoration:none;width:89%;min-width:86%;display:block;font-size:28px;font-family:Helvetica,Arial,sans-serif;color:#000000;"> <strong>GamiSE</strong> </td> </tr> <tr> <td class = "text" style="padding: 0px;font-family: Arial, Helvetica, sans-serif;font-weight: 600;color: #292f33;font-size: 32px;line-height: 36px;padding: 0px;">Daily Email </td> </tr> <tr> <br> </tr> <tr> <td class = "text" style="padding: 0px;font-family: Arial, Helvetica, sans-serif;font-weight: 600;color: #292f33;font-size: 24px;line-height: 36px;padding: 0px;">Hello, """ + user.username + """</td> </tr> <tr> <br> </tr> <tr> <td align="center" style="padding: 0px"> <table cellpading="0" cellspacing="0" border="0" width="100%" style="padding: 0px"> <tbody> <tr> <td style="padding: 0px;border: 1px solid #aab8c2;background-color: #ffffff;border-radius: 4px"> <table cellpadding="0" cellspacing="0" border="0" width="100%" style="padding: 0px"> <tbody> <tr> <td style="padding: 0px"> <table cellpadding="0" cellspacing="0" border="0" width="100%" style="padding: 0px"> <tbody> <tr> <td width="12" style="padding: 0px;width: 24px;min-width: 12px"></td> <td style="padding: 0px"> <table cellpadding="0" cellspacing="0" border="0" width="100%" style="padding: 0px"> <tbody> <tr> <td style="text-decoration:none;width:89%;min-width:86%;display:block;font-size:28px;font-family:Helvetica,Arial,sans-serif;color:#000000;padding: 0px;"> Experience sharing: </td> <td style="text-decoration:none;width:89%;min-width:86%;display:block;font-size:18px;font-family:Helvetica,Arial,sans-serif;color:#000000;padding: 0px;"> Do you have any experience or defending tips that related to social engineering and want to share on the GamiSE? Feel free to share your experience to help others defending the attacks. </td> </tr> <tr> <td valign="middle" style="padding: 0px;border-radius: 100px;line-height: 18px;"> <br> <a href=""" + url_for('pexperience', token=uniquelink, _external=True) + """ style="text-align:center;width:30%;min-width:20%;display:block;font-size:18px;font-family:Helvetica,Arial,sans-serif;color:#ffffff;text-decoration:none;padding:5px 18px;border:1px solid#3071A9;background-color: #3071A9; display:inline-block;font-weight:bold;white-space:nowrap"> Share on GamiSE </a> <br><br><hr> </td> </tr> <tr> <td height="14" style="height: 14px;padding: 0px"></td> </tr> <tr> <td style="text-decoration:none;width:89%;min-width:86%;display:block;font-size:28px;font-family:Helvetica,Arial,sans-serif;color:#000000;padding: 0px;"> Submit a Report: </td> <td style="text-decoration:none;width:89%;min-width:86%;display:block;font-size:18px;font-family:Helvetica,Arial,sans-serif;color:#000000;padding: 0px;"> Do you have face any attacks recently, or do you find any phishing email elements in the emails that you received these days? After you forward the phishing email to the IT department, would you like to submit a report to help the IT department to analyze the social enginering attacks? </td> </tr> <tr> <td valign="middle" style="padding: 0px;border-radius: 100px;line-height: 18px;"> <br> <a href=""" + url_for('userreport', token=uniquelink, _external=True) + """ style="text-align:center;width:30%;min-width:20%;display:block;font-size:18px;font-family:Helvetica,Arial,sans-serif;color:#ffffff;text-decoration:none;padding:5px 18px;border:1px solid#3071A9;background-color: #3071A9; display:inline-block;font-weight:bold;white-space:nowrap"> Report on GamiSE </a> <br><br><hr> </td> </tr> <tr> <td style="padding: 0px"> <br> <table cellpadding="0" cellspacing="0" border="0" width="100%" style="padding: 0px"> <tbody> <tr> <td style="text-decoration:none;width:89%;min-width:86%;display:block;font-size:28px;font-family:Helvetica,Arial,sans-serif;color:#000000;padding: 0px;"> News: </td> </tr> <tr> <td style="padding: 0px;"> <br> <img src = """ + image_url + """ width="598.89" height="399.25"> </td> </tr> <tr> <td height="14" style="height: 14px;padding: 0px"></td> </tr> <tr> <td height="8" style="height: 8px;padding: 0px;"></td> </tr> <tr> <td style="padding: 0px;font-family: Arial, Helvetica, sans-serif;font-size: 20px;line-height: 24px;font-weight: bold;color: #292f33;"> """ + title + """ </td> </tr> <tr> <td height="8" style="height: 8px;padding: 0px;"></td> </tr> <tr> <td style="padding: 0px;font-family: Arial, Helvetica, sans-serif;font-size: 14px;line-height: 18px;color: #292f33;"> """ + description + """ </td> </tr> <tr> <td height="14" style="height: 14px;padding: 0px;"></td> </tr> <tr> <td style="padding: 0px;"> <table border="0" cellspacing="0" cellpadding="0" align="left" width="100%" style="padding: 0px;"> <tbody> <tr> <td valign="middle" style="padding: 0px;border-radius: 100px;line-height: 18px;"> <br> <a href=""" + link + """ style="text-align:center;width:20%;min-width:10%;display:block;font-size:18px;font-family:Helvetica,Arial,sans-serif;color:#ffffff;text-decoration:none;padding:5px 18px;border:1px solid#3071A9;background-color: #3071A9; display:inline-block;font-weight:bold;white-space:nowrap"> Read More </a> <br><br><hr> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> </td> </tr> <tr> <td style="text-decoration:none;width:89%;min-width:86%;display:block;font-size:28px;font-family:Helvetica,Arial,sans-serif;color:#000000;padding: 0px;"> Want to Withdrawal: </td> <td style="text-decoration:none;width:89%;min-width:86%;display:block;font-size:18px;font-family:Helvetica,Arial,sans-serif;color:#000000;padding: 0px;"> <br> If you don't want to use GamiSE anymore, please click the link to submit a withdrawal questionnaire to the GamiSE, then withdrawal the training. </td> </tr> <tr> <td valign="middle" style="padding: 0px;border-radius: 100px;line-height: 18px;"> <br> <a href=""" + url_for('withdrawal', token=uniquelink, _external=True) + """ style="text-align:center;width:30%;min-width:20%;display:block;font-size:18px;font-family:Helvetica,Arial,sans-serif;color:#ffffff;text-decoration:none;padding:5px 18px;border:1px solid#3071A9;background-color: #3071A9; display:inline-block;font-weight:bold;white-space:nowrap"> Request a Withdrawal </a> <br><br> </td> </tr> </tbody> </table> </td> <td width="24" style="padding: 0px;width: 24px;min-width: 12px;"></td> </tr> </tbody> </table> </td> </tr> <tr> <td height="20" style="padding: 0px; height: 20px"></td> </tr> </tbody> </table> </a> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> </html> """, subtype='html') with smtplib.SMTP_SSL('smtp.fastmail.com', 465) as smtp: smtp.login(EMAIL_USERFASTMAIL, EMAIL_PASSWORDFASTMAIL) time.sleep(2) smtp.send_message(msg) print(user.email) return user, title, image_url, description, link, uniquelink
def send_email_credential(user): """ Send credentials to user :param user: :class:`labresult.model.User` """ if not user.email : labresult.app.logger.warning("%s has no email" % user.email) return False # wait ten minutes between to sending for message in [ m for m in user.messages if m.title == "credential" and m.channel == "email" ]: if (now() - message.date) < timedelta( minutes=get_option('crendential_email.tempo', 10, gettext("Minutes avant l'envoi d'un deuxieme email"))): labresult.app.logger.warning("Credential email already sent to %s" % user.email) return True # Create the base text message. msg = EmailMessage() msg['Subject'] = get_option("credential_email.title", gettext("Accès à mes résultats")) msg['From'] = Address("", get_option('crendential_email.from_address', "*****@*****.**", gettext("Adresse email de l'envoyeur."), ) ) msg['To'] = (Address("", user.email),) #generate txt from html template = get_option("credential_email.html_content", credential.html_content, gettext("Contenu du mail d'authentification"), ) txt_content = re.sub("<[^>]+>", "", template.replace("<br>",'\n').format(code=user.credential_code, logo_cid="")) msg.set_content(txt_content) logo_cid = str(uuid.uuid4()) msg.add_alternative(template.format(logo_cid=logo_cid, code = user.credential_code), 'html', 'utf-8') # Now add the related image to the html part. default_logo = open(os.path.join(os.path.dirname(__file__), "data", "logo.png"), 'rb').read() logo = get_option("credential_email.logo", default_logo) msg_image = MIMEImage(logo, name='logo.png', _subtype="image/png" ) msg.attach(msg_image) msg_image.add_header('Content-ID', '<{}>'.format(logo_cid)) # Send the message via local SMTP server. try : with smtplib.SMTP_SSL(get_option("smtp_server")) as s: s.login(get_option("smtp_login"), get_option("smtp_password")) s.send_message(msg) log_message(user, "credential", "email", get_option("smtp_server"), txt_content) return True except Exception : error = traceback.format_exc() labresult.app.logger.error(error) return False
class EmailTemplate: _template = ("<h3>{name}({grocery})</h3>" "<div><a href='{link}'><img src='cid:{cid}'></a></div>" "<div><p>价格:¥{price}; 发布日期:{publish}</p></div>" "<hr>") def __init__(self, html): assert isinstance(html, str) self.soup = BeautifulSoup(html, "html.parser") self.message = EmailMessage() self.message["From"] = CONFIG["sender"] self.message["To"] = ",".join(CONFIG["receivers"]) self.message["Subject"] = CONFIG["subject"] def lis(self): for li in self.soup.select("ul[id=feed-main-list] li"): yield li @staticmethod def channel(li): # 商品所属购物频道 return li.select_one("div[class=z-feed-img] span").string """ @staticmethod def next(li): return li.select_one("div[class=feed-link-btn-inner] a")[0] """ @staticmethod def data(li): # 商品在购物平台中的地址 go_buy = li.select_one("div[class=feed-link-btn-inner] a") data = re.findall(r"push\((.*?)\)", go_buy["onclick"])[1] return json.loads(data.replace("'", '"')) @staticmethod def link(li): # 商品在 smzdm 中的地址 return li.select_one("div[class=z-feed-img] a").get("href", "").strip() @staticmethod def publish(li): # 商品发布日期 return li.select_one( "span[class=feed-block-extras]").contents[0].strip() @staticmethod def img(li): # 商品图片地址 img_src = li.select_one("div[class=z-feed-img] a img").get("src", "") if img_src.startswith("//"): img_src = "https:" + img_src else: # TODO: gift img_src = "" return _session.get(img_src, headers=HEADERS).content @staticmethod def cid(): return make_msgid()[1:-1] @error_handler def _generate(self, li): cid = self.cid() img = self.img(li) data = self.data(li) tmpl = self._template.format(**{ "cid": cid, # 商品名 "name": data.get("ecommerce", {}).get("add", {}) \ .get("products", [{}])[0].get("name", "暂无").strip(), # 商品价格 "price": data.get("ecommerce", {}).get("add", {}) \ .get("products", [{}])[0].get("price", "暂无"), # 商品所属购物平台 "grocery": data.get("ecommerce", {}).get("add", {}) \ .get("products", [{}])[0].get("dimension12", "暂无").strip(), "link": self.link(li), "publish": self.publish(li), }) self.message.add_alternative(tmpl, subtype="html") self.message.get_payload()[-1].add_related(img, "image", "png", cid=cid) def generate(self): for li in self.lis(): if self.channel(li) in TARGET["channels"]: self._generate(li) return self.message
'*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**' ] msg['Subject'] = "Password Change Detected!!" msg['From'] = "*****@*****.**" msg['To'] = contacts # msg.set_content('The password was changed') msg.add_alternative(f"""\ <!DOCTYPE html> <html> <body> <div class="pass-change" style="font-family:'Times New Roman', Times, serif; background-color: rgb(31, 20, 20); text-align: center; border-radius: 10px; padding: 10px;"> <p class="header" style="font-family: Georgia, 'Times New Roman', Times, serif; font-size: 40px; font-weight: bold; color: white;">Hello, Team Automated!!</p> <p class="second-head" style="font-size: 30px; font-weight: bold; color: red;">An important mail from SASHA.</p> <p class="content" style=" font-size: 20px; color: wheat;"> The password for SASHA is changed to '{password}' by {nm} at {datetime.datetime.now()}. </p> </div> <div class="footer" style=" text-align: center; color: black;"> This is an auto-generated mail. Do not reply to this thread. <br> Copyright © SASHA, Team_Automated, 2020. </div> </body> </html> """, subtype='html') server.login("*****@*****.**", "SASHAsasha") server.send_message(msg) server.quit() bot.send_message( chat_id, "Password changed successfully!! Please enter your command now!"
def sendStockStatus(self, product, status): if status != 'In Stock': EMAIL_ADDRESS = "*****@*****.**" EMAIL_PASSWORD = "******" msg = EmailMessage() msg['Subject'] = f'Stock Update-{product[0]}' msg['From'] = EMAIL_ADDRESS msg['To'] = '*****@*****.**' msg.add_alternative(f"""\ <!DOCTYPE html> <html> <body style="width: 600px;margin: 0 auto;" cz-shortcut-listen="true"> <div style="width:500px;margin: 30px auto;"> <div style=" background-color: #43425D; color: white; padding: 20px; text-align: center; "> <h1>{status} Alert</h1> </div> <div style=" padding: 5px; "> <p><span><b>Hi Admin<br><br></b></span>A product is <span style='background-color: black; color: white; padding: 5px 5px;'>{status}</span> Product details are shown below for your reference:</span></p> </div> <div style=" padding: 4px; "> <h2>Product Details</h2> </div> <table style=" width: 100%; border-collapse: collapse; text-align: center; "> <thead style="background-color: #3B86FF;"> <tr> <th style=" border: 1px solid black; padding: 10px; ">Product</th> <th style=" border: 1px solid black; padding: 10px; ">SKU</th> <th style=" border: 1px solid black; padding: 10px; ">Available Stock</th> </tr> </thead> <tbody> <tr> <td style=" text-align: left; border: 1px solid black; padding: 10px; ">{product[0]}</td> <td style=" border: 1px solid black; padding: 10px; ">{product[1]}</td> <td style=" border: 1px solid black; padding: 10px; ">{product[4]}</td> </tr> </tbody> </table> <div style=" margin-top: 50px; background: #eeeded; "> <p style=" opacity: 50%; padding: 30px; font-style: italic; ">Sent by automatic stock status sending function in dbfns.py file</p> </div> </div> </body> </html> """, subtype='html') try: with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD) smtp.send_message(msg) print('mail sent') except Exception as e: print(str(e))
--Pepé """) # Add the html version. This converts the message into a multipart/alternative # container, with the original text message as the first part and the new html # message as the second part. asparagus_cid = make_msgid() msg.add_alternative("""\ <html> <head></head> <body> <p>Salut!</p> <p>Cela ressemble à un excellent <a href="http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718"> recipie </a> déjeuner. </p> <img src="cid:{asparagus_cid}" /> </body> </html> """.format(asparagus_cid=asparagus_cid[1:-1]), subtype='html') # note that we needed to peel the <> off the msgid for use in the html. # Now add the related image to the html part. with open("roasted-asparagus.jpg", 'rb') as img: msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg', cid=asparagus_cid)
# We are done sys.exit(0) # OK; send the emails :D import smtplib from email.message import EmailMessage from email.headerregistry import Address from email.utils import make_msgid for email in sorted(emails_to_send.keys()): msg = EmailMessage() msg['Subject'] = 'OpenModelica Library Testing Regressions' msg['From'] = Address("OM Hudson", "openmodelicabuilds", "ida.liu.se") msg['To'] = email msg.set_content("""\ The following reports contain regressions your account was involved with: """ + "\n".join(reversed(emails_to_send[email]["plain"]))) msg.add_alternative("""\ <html> <head></head> <body> <p>The following reports contain regressions your account was involved with:</p> %s </body> </html> """ % "\n".join(reversed(emails_to_send[email]["html"])), subtype='html') with smtplib.SMTP('test.openmodelica.org') as s: s.send_message(msg)