def _get_rehydrated_headers(self): headers = self.headers if headers is None: return EmailMessage() return email.message_from_string(headers)
import smtplib from email.message import EmailMessage from_email = '*****@*****.**' password = '******' mes = EmailMessage() mes['Subject'] = "Im a Subject" mes['From'] = from_email mes['To'] = '*****@*****.**' mes.set_content(" Im the content of the email.") mes.add_alternative("""\ <!DOCTYPE html> <html> <body style="text-align: center;"> <img src="http://skilldisk.com/static/image/sigma.png" alt="Skill-Disk-Logo" style="height: 50px;"> <h1 style="color:#ffaa00;">Skill Disk</h1> <h4 style="color:#2a2a2a;"> Webinar on Automate boring stuff using pyton </h4> <br> <hr> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker
def send_msg(self, body, who, subject=None, **kwargs): """Sends email and SMS messages. **NOTES FOR TARGETING RECIPIENTS WITH 'who':** - `'who'` can be a user name, group name, email, or mobile number. - It can be an individual item or a list of items. - User and group names are defined in ``contact_list.json``. - When targeting users or groups, you can toggle the mode of communication using `use_email` and `use_sms`. By default, only SMS is used. - Mobile numbers can be any format, but they must contain 10 digits in addition to any leading 0s or 1s. Integers and strings are OK. Arguments: body (str): Contents of message. who (obj): User name, group name, email, or mobile number. Single items, or a list of many. See notes. subject (str): Optional. Subject of message. Default is None. Keyword Arguments: attachment (Path): Path-like object that points to a file. Default is None. disable_email (bool): If True, emails will not be sent to any recipients. This can be useful if you want to send only SMS messages to users or groups in the contact_list.json. Default is False. disable_sms (bool): If True, SMS messages will not be sent to any recipients. This can be useful if you want to send only email messages to users or groups in the contact_list.json. Default is False. Returns: No returns. """ # ============================================================ # Parse and bail out if needed # ============================================================ self._parse_who(who) if not self._ensure_recipients_exist(): return # Kwargs attachment = kwargs.get('attachment', None) disable_email = kwargs.get('disable_email', False) disable_sms = kwargs.get('disable_sms', False) if not self._ensure_attachment_exists(attachment): return for b, n in zip([disable_email, disable_sms], ['disable_email', 'disable_sms']): if not isinstance(b, bool): msg = f'\'{n}\' must be boolean but you gave type {type(b)}' raise TypeError(msg) # ============================================================ # Main # ============================================================ with self._setup_smtp_server() as sess: # Create msg object msg = EmailMessage() # Personalize the template body_from_template = self.template.substitute(BODY=body) # Set msg parameters; # Note we will assign msg['To'] below when iterating over email addresses msg['From'] = self.sender_address msg['Subject'] = subject.upper() if isinstance(subject, str) else None # Copy outgoing emails to cc list if isinstance(self.cc_email_list, list): if len(self.cc_email_list) > 0: msg['CC'] = ','.join(self.cc_email_list) # Base text message msg.set_content(body_from_template) # HTML version body_html = re.sub(r'[\n]', '<br>', body_from_template) # Replace /n with <br> logo_cid = make_msgid() msg.add_alternative("""\ <html> <head></head> <body> <p>""" + body_html + '</p>' + """ <a href="https://www.liveline.tech"> <img src="cid:{logo_cid}" /> </a> </body> </html> """.format(logo_cid=logo_cid[1:-1]), subtype='html') # Add logo to the HTML version if EMAIL_SIGNATURE_LOGO_FILE is not None: t = root / EMAIL_SIGNATURE_LOGO_FILE if t.exists(): with open(t, 'rb') as img: r = img.read() # noinspection PyUnresolvedReferences msg.get_payload()[1].add_related(r, 'image', 'png', cid=logo_cid) # Optionally attach a file # First use mimetypes to try and guess content type based on file extension: if attachment is not None: attachment = Path(attachment) ctype, encoding = mimetypes.guess_type(str(attachment)) 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) maintype += f'; name="{attachment.name}"' with open(attachment, 'rb') as file: r = file.read() msg.add_attachment(r, maintype=maintype, subtype=subtype) # ============================================================ # Email # ============================================================ # For each email & phone in current lists, send messages if not disable_email: for e in self.current_email_list: # Console out stdout_msg = f'COMMUNICATOR MESSAGE: Sending email to: ' fancy_print(stdout_msg, fg=COMMUNICATOR_MSG_COLOR, end='') fancy_print(e, fg='hlink') # Update msg 'To:' field if msg['To'] is not None: del msg['To'] msg['To'] = e # # Make a local copy of what we are going to send... to a log file? # with open('outgoing.msg', 'wb') as f: # f.write(bytes(msg)) try: sess.send_message(msg) except: stdout_msg = f'COMMUNICATOR WARNING: Failed sending email message' fancy_print(stdout_msg, fg=COMMUNICATOR_WARN_COLOR) # ============================================================ # SMS # ============================================================ if not disable_sms: for m in self.current_mobile_list: # Console out stdout_msg = f'COMMUNICATOR MESSAGE: Sending SMS message to: ' fancy_print(stdout_msg, fg=COMMUNICATOR_MSG_COLOR, end='') fancy_print(m[0:3] + '.' + m[3:6] + '.' + m[6:10], fg='cerulean') any_ok = False candidates = list() # Try all the stubs! # We don't know the carrier name. # Assume the invalid addresses will get black-holed by the various carriers. for stub in self.sms_email_stubs: candidates.append(m + self.sms_email_stubs[stub]) # Update msg 'To:' field if msg['To'] is not None: del msg['To'] msg['To'] = candidates # # Make a local copy of what we are going to send... to a log file? # with open('outgoing.msg', 'wb') as f: # f.write(bytes(msg)) try: sess.send_message(msg) any_ok = True except: pass if not any_ok: stdout_msg = f'COMMUNICATOR WARNING: Failed sending SMS message' fancy_print(stdout_msg, fg=COMMUNICATOR_WARN_COLOR) return
details = [] with open('confidential.txt', 'r') as f: for x in f: details.append(x) email_addr = details[0][6:-1] password = details[1][6:-1] reciever = details[2][6:-1] nws = '' for i in range(len(news.head)): nws += '***********************************************************************************\n' for h, l in zip(news.head[i], news.link[i]): nws += str(h) + "--->" + '(' + str(l) + ')' + '\n' # msg = MIMEMultipart("alternative") msg = EmailMessage() msg['Subject'] = 'NEWZZ UPDATE' msg['From'] = email_addr msg['To'] = reciever msg.set_content(nws) # Create the plain-text and HTML version of your message # html = """\ # <!DOCTYPE html> # <html> # <body> # <p>Hi,<br> # How are you?<br> # <a href="http://www.realpython.com">Real Python</a> # has many great tutorials.
def post_send(self, subject="", from_addr: str = None, from_name: str = '', to_addrs: [str] = None, cc_addrs: [str] = None, bcc_addrs: [str] = None, body="", attachments: [FileParam] = None, attachment_urls: dict = None, subtype="plain", starttls=True): """ Send mail. To send attachments, add files in the body of the request as multipart/form-data. """ from_addr = from_addr or os.getenv('from_addr') if not from_addr: return "From address not defined (from_addr:str)", 400 to_addrs = to_addrs or os.getenv('to_addrs') if not to_addrs: return "To addresses not defined (to_addrs:[str])", 400 # Creates email try: from_ = formataddr((from_name if from_name else False, from_addr)) msg = EmailMessage() msg['Subject'] = subject msg['From'] = from_ msg['To'] = to_addrs if isinstance(to_addrs, str) else ', '.join(to_addrs) if cc_addrs: msg['Cc'] = cc_addrs if isinstance( cc_addrs, str) else ', '.join(cc_addrs) if bcc_addrs: msg['Bcc'] = bcc_addrs if isinstance( bcc_addrs, str) else ', '.join(bcc_addrs) msg.set_content(body, subtype=subtype) if attachments: if not isinstance(attachments, list): attachments = [attachments] for attachment in attachments: if not attachment.mime_type: return f"Mime type of the attachment {attachment.file.name} is not defined.", 400 maintype, subtype = attachment.mime_type.split("/") msg.add_attachment(attachment.file.read(), maintype=maintype, subtype=subtype, filename=attachment.file.name) if attachment_urls: for attachment_name, attachment_url in attachment_urls.items(): response = requests.get(attachment_url) if response.status_code == 200: attachment = response.content maintype, subtype = response.headers[ 'Content-Type'].split('/') msg.add_attachment(attachment, maintype=maintype, subtype=subtype, filename=attachment_name) else: return f"Failed to download attachment, error {response.status_code}.", 400 except Exception as e: return f"Cannot create email message (Error: {str(e)}).", 400 # Send email try: with smtplib.SMTP(self.smtp_server) as server: if starttls: server.starttls() server.login(self.smtp_login, self.smtp_passwd) server.send_message(msg) return f"Mail sent to {msg['To']}" except smtplib.SMTPAuthenticationError: return "Wrong username/password : cannot connect.", 400 except Exception as e: return f"Cannot send email message (Error: {str(e)}).", 400
def test_str_defaults_to_utf8(self): m = EmailMessage() m['Subject'] = 'unicöde' self.assertEqual(str(m), 'Subject: unicöde\n\n')
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'] = 'Andrei Neagoie' email['to'] = '<to email address>' email['subject'] = 'Python is good and powerful!' email.set_content(html.substitute({'name': 'TinTin'}), 'html') with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp: smtp.ehlo() smtp.starttls() smtp.login('<your email address>', '<your password>') smtp.send_message(email) print('all good boss!')
def __init__(self): self._msg = EmailMessage() self._recipients = []
def send(name1, email1, number1): try: now = datetime.now() current_time = now.strftime("%H:%M %p") checkin1 = current_time + " IST" # enter user in database user1 = User(name=name1, email=email1, number=number1, checkin=checkin1) db.session.add(user1) db.session.commit() message = "Visitor Details\n" + "Name -" + name1 + "\nEmail - " + email1 + "\nNumber - " + number1 host = Host.query.first() host_number = host.number host_email = host.email user1.hostname = host.name db.session.commit() #sending sms using Fast2sms url = "https://www.fast2sms.com/dev/bulk" querystring = { "authorization": "KMviuAdxhlzpT2tPYXse16QV9n7JWUr5Rm4oBgCkf0LSHajGZ8r3ZIXj96dqFlvLUAneVcMWJgCYtSwh", "sender_id": "FSTSMS", "message": message, "language": "english", "route": "p", "numbers": host_number } headers = {'cache-control': "no-cache"} response = requests.request("GET", url, headers=headers, params=querystring) print(response.text) #sending mail via gmail s = smtplib.SMTP('smtp.gmail.com', 587) s.starttls() sender_id = "*****@*****.**" msg = EmailMessage() msg['Subject'] = 'Visitor Details' msg['From'] = sender_id msg['To'] = host_email # msg.set_content(message) html_message = open('templates/html_email_host.html').read().format( name=name1, email=email1, number=number1) msg.add_alternative(html_message, subtype='html') s.login(sender_id, "qKHcnWwBEkL8g96") s.send_message(msg) s.quit() host1 = Host.query.first() host_number = host1.number Host.query.filter_by(number=host_number).delete() db.session.commit() return -1 except: try: host = Host.query.first() host_number = host.number return 1 except: return 2
def build_reminder_mail(name: str, index_id: str, counts: Dict[str, Dict[str, int]]) -> EmailMessage: msg = EmailMessage() # set the plain text body text = """ Hello {name}! This is a friendly reminder from VIINC. Here is a report on your interaction with our data entry process. The more questions you answer and the more frequently you update your answers the better your Vitality Index will represent your current state of health and well-being. Total Questions answered: {tanswered}/{ttotal} Medical: {manswered}/{mtotal} Nutrition: {nanswered}/{ntotal} Exercise: {eanswered}/{etotal} Perception: {panswered}/{ptotal} Social: {sanswered}/{stotal} Thank you and please come back to http://www.vitalityindex.com often. Be Healthy | Be Happy | Be Your Best """.format(name=name, tanswered=counts[index_id]['answered'], ttotal=counts[index_id]['total'], manswered=counts['MEDICAL']['answered'], mtotal=counts['MEDICAL']['total'], nanswered=counts['NUTRITION']['answered'], ntotal=counts['NUTRITION']['total'], eanswered=counts['EXERCISE']['answered'], etotal=counts['EXERCISE']['total'], panswered=counts['PERCEPTION']['answered'], ptotal=counts['PERCEPTION']['total'], sanswered=counts['SOCIAL']['answered'], stotal=counts['SOCIAL']['total']) msg.set_content(text) html = """ <html lang="en"> <head> <meta charset="UTF-8"> <title>Hello</title> </head> <body> <h1>Hello {name}!</h1> <p>This is a friendly reminder from VIINC. Here is a report on your interaction with our data entry process. The more questions you answer and the more frequently you update your answers the better your Vitality Index will represent your current state of health and well-being. </p> <table> <tr><td>Total Questions answered:</td><td>{tanswered}/{ttotal}</td></tr> <tr></tr> <tr><td>Medical:</td><td>{manswered}/{mtotal}</td></tr> <tr><td>Nutrition:</td><td>{nanswered}/{ntotal}</td></tr> <tr><td>Exercise:</td><td>{eanswered}/{etotal}</td></tr> <tr><td>Perception:</td><td>{panswered}/{ptotal}</td></tr> <tr><td>Social:</td><td>{sanswered}/{stotal}</td></tr> </table> <p>Thank you and please come back to our <a href="http://www.vitalityindex.com">website</a> often. </p> <h2>Be Healthy | Be Happy | Be Your Best</h2> </body> </html> """.format(name=name, tanswered=counts[index_id]['answered'], ttotal=counts[index_id]['total'], manswered=counts['MEDICAL']['answered'], mtotal=counts['MEDICAL']['total'], nanswered=counts['NUTRITION']['answered'], ntotal=counts['NUTRITION']['total'], eanswered=counts['EXERCISE']['answered'], etotal=counts['EXERCISE']['total'], panswered=counts['PERCEPTION']['answered'], ptotal=counts['PERCEPTION']['total'], sanswered=counts['SOCIAL']['answered'], stotal=counts['SOCIAL']['total']) msg.add_alternative(html, subtype='html') return msg
def build_welcome_mail(name: str) -> EmailMessage: msg = EmailMessage() # set the plain text body text = """ Welcome! Congratulations {name} and welcome to VIINC and the path to a happier you! HAPPINESS - we all strive for it. But it seems we are pretty bad at achieving it. In fact what is it? Many of the things we intuitively think bring happiness in fact do not. It’s one of those things we think we know what it is but have a hard time describing and an even harder time living. Our mission is to help you change that. It is an ambitious goal but we are passionate about it. We are also science and technology driven and luckily great strides have been made in both fields. We are leveraging tools and insights from various scientific disciplines and combine them in a holistic and highly individualized approach. Happiness after all is an intensely holistic emotion that depends on physical and mental factors - and it is also intensely personal. Despite the advances in science and technology there is still a lot that is not yet known or well understood and part of our mission is to advance the science of happiness and share our insights with our community of users. Happiness has been directly linked to health and longevity and vice versa. Helping you improve, no matter how much or little, holds the promise of significantly impacting your life and the happiness and health of society as a whole. But where to start? You have taken a critical first step by registering on our website and answering the first 20 questions. The data we collect through these questions serves to establish a holistic and highly personalized base line for your Vitality Index (VI) Score. The Vitality Index provides a snapshot of your current state of happiness, health and well-being. It breaks it down into five dimensions. Combined these dimensions provide the basis for holistic health and with that the foundation for happiness and well- being. You can also see how you stack up to others. Enjoy the insight! Now, here is where we need YOUR help. We are a young company and we are just getting started with an ambitious vision to help people live happier, healthier and more fulfilled lives. We have great ideas how to put novel science and technology to work for all of us. In doing so, we are keenly interested in your feedback to guide our future development efforts. So please help us by filling out a short questionnaire. http://www.123formbuilder.com/form-4093826/user-survey Thank you and please come back to our https://www.vitalityindex.com often to answer more questions and update ones you have already answered. The more questions you answer and the more frequently you update your answers the better the Vitality Index will reflect your current state of well-being. Be Healthy | Be Happy | Be Your Best """.format(name=name) msg.set_content(text) html = """ <html lang="en"> <head> <meta charset="UTF-8"> <title>Welcome</title> </head> <body> <h1>Welcome!</h1> <p>Congratulations {name} and welcome to VIINC and the path to a happier you! HAPPINESS - we all strive for it. But it seems we are pretty bad at achieving it. In fact what is it? Many of the things we intuitively think bring happiness in fact do not. It’s one of those things we think we know what it is but have a hard time describing and an even harder time living. </p> <p>Our mission is to help you change that. It is an ambitious goal but we are passionate about it. We are also science and technology driven and luckily great strides have been made in both fields. We are leveraging tools and insights from various scientific disciplines and combine them in a holistic and highly individualized approach. Happiness after all is an intensely holistic emotion that depends on physical and mental factors - and it is also intensely personal. </p> <p>Despite the advances in science and technology there is still a lot that is not yet known or well understood and part of our mission is to advance the science of happiness and share our insights with our community of users. Happiness has been directly linked to health and longevity and vice versa. Helping you improve, no matter how much or little, holds the promise of significantly impacting your life and the happiness and health of society as a whole. </p> <p>But where to start? You have taken a critical first step by registering on our website and answering the first 20 questions. The data we collect through these questions serves to establish a holistic and highly personalized base line for your Vitality Index (VI) Score. The Vitality Index provides a snapshot of your current state of happiness, health and well-being. It breaks it down into five dimensions. Combined these dimensions provide the basis for holistic health and with that the foundation for happiness and well- being. </p> <p>You can also see how you stack up to others. Enjoy the insight! </p> <p>Now, here is where we need YOUR help. We are a young company and we are just getting started with an ambitious vision to help people live happier, healthier and more fulfilled lives. We have great ideas how to put novel science and technology to work for all of us. In doing so, we are keenly interested in your feedback to guide our future development efforts. So please help us by filling out a short questionnaire. <br><br> <a href="http://www.123formbuilder.com/form-4093826/user-survey">User Survey</a> </p> <p>Thank you and please come back to our <a href="https://www.vitalityindex.com">website</a> often to answer more questions and update ones you have already answered. The more questions you answer and the more frequently you update your answers the better the Vitality Index will reflect your current state of well-being. </p> <h2>Be Healthy | Be Happy | Be Your Best</h2> </body> </html> """.format(name=name) msg.add_alternative(html, subtype='html') return msg
def __init__(self): self.server = smtplib.SMTP_SSL('smtp.gmail.com', 465) self.msg = EmailMessage() #date and time format: dd/mm/YYYY H:M:S self.format = "%d/%m/%Y %H:%M:%S"
def find_jobs(): html_text = requests.get( 'https://www.timesjobs.com/candidate/job-search.html?searchType=personalizedSearch&from=submit&txtKeywords=python&txtLocation=' ).text soup = BeautifulSoup(html_text, 'lxml') jobs = soup.find_all('li', class_="clearfix job-bx wht-shd-bx") for index, job in enumerate(jobs): published_date = job.find('span', class_='sim-posted').span.text #if '1' in published_date or '2' in published_date or '3' in published_date: company_name = job.find('h3', class_='joblist-comp-name').text.replace( ' ', '') required_skills = job.find('span', class_='srp-skills').text.replace( ' ', '').split() required_skills_list = (required_skills[0]).split(',') description_link = job.header.h2.a['href'] html_description = requests.get(description_link).text soup_2 = BeautifulSoup(html_description, 'lxml') description = soup_2.find('div', class_="jd-desc job-description-main").text published_date = job.find('span', class_='sim-posted').span.text #applications_received='' #try: # applications_received=soup_2.find('strong',class_='ng-binding').text #except: # pass #check = all(item in familiar_skills_list for item in required_skills_list) #if check is True: #with open (f'posts/{index}.txt','w') as f: #f.write('') #f.write(f'JOB NO.{index} \n') #f.write(f'Company name: {company_name.strip()} \n') #f.write(f'Required skills: {required_skills[0]} \n') #f.write(f'Published Date: {published_date.strip()} \n') #f.write(f'Description: {description}') #f.write('') #print(f'File Saved: {index}') #print(company_name.strip()) #print(required_skills[0]) #print(published_date.strip()) aasheet.write(index + 1, 0, company_name.strip()) aasheet.write(index + 1, 1, required_skills[0]) aasheet.write(index + 1, 2, published_date.strip()) #aasheet.write(index+1,3,html_description) #aasheet.write(index+1,4,applications_received) #aasheet.write(index+1,3,description) print(f'File Saved: {index}') print(html_description) for i in range(3): max_length = get_column_width(aasheet, i) try: set_column_autowidth(aasheet, i, max_length + 1) except: pass aa.close() EMAIL_ADDRESS = os.environ.get('EMAIL_USER') EMAIL_PASSWORD = os.environ.get('EMAIL_PASS') #NEXT STEPS : DESCRIPTION COLUMN (LINK TO IT); QUESTIONS AT THE BEGINNING (SELECT COUNTRIES TO WORK AT) (SELECT CURRENCY) (RANGE OF SALARY) (WORDS YOU WANT INCLUDED IN THE DESCRIPTION) msg = EmailMessage() msg['Subject'] = 'Test' msg['From'] = EMAIL_USER msg['To'] = '*****@*****.**' #msg.set_content('This is a plain text email') #files=['resume.pdf'] #for file in files: with open('aa.xlsx', 'rb') as f: file_data = f.read() file_name = f.name msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name) #msg.add_alternative("""\ #<!DOCTYPE html> #<html> # <body> # <h1 style="color:SlateGray;">test passed successfully!</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 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) 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
def processQueue(): while True: emailAddr = "" # This is so we don't send an email to a previous person incase it fails before it pops off the queue try: mutex.acquire() #Queue is empty wait to check again if not submissionQueue: mutex.release() time.sleep(5) else: filePath, emailAddr = submissionQueue.pop(0) mutex.release() cFiles: List[HookFile] = [] cWhitelist: List[HookFile] = [] javaFiles: List[HookFile] = [] javaWhitelist: List[HookFile] = [] num_files = 0 start = time.time() with tar.open(filePath, mode='r') as tarFile: for fileName in tarFile.getnames(): num_files+=1 if tarFile.getmember(fileName).isfile(): #Break up the file path into it's respective folders filePathElements: List[str] = os.path.normpath(fileName).split(os.sep) ext = fileName[fileName.rfind('.'):] #This is a previous years submission so we need to use it to check for plagiarism but not actually #check for plagiarism in this file if filePathElements[0] == 'PreviousYears': owner = filePathElements[1].split('_')[-1] #Get the student hash in the folder name if ext == ".java": #If it's a java file then add it to the java list javaFiles.append(HookFile(fileName, owner, HookFileType.PREVIOUS_YEAR, tarFile.extractfile(fileName).read().decode('utf-8'))) elif ext == ".cpp" or ext == ".c" or ext == ".hpp" or ext == ".h": #If it's a C/C++ file add it to the C list cFiles.append(HookFile(fileName, owner, HookFileType.PREVIOUS_YEAR, tarFile.extractfile(fileName).read().decode('utf-8'))) # This is a current year submission so we need to actually check for plagiarism in it elif filePathElements[0] == 'CurrentYear': owner = filePathElements[1].split('_')[-1] #Get the student hash in the folder name if ext == ".java": javaFiles.append(HookFile(fileName, owner, HookFileType.CURRENT_YEAR, tarFile.extractfile(fileName).read().decode('utf-8'))) elif ext == ".cpp" or ext == ".c" or ext == ".hpp" or ext == ".h": cFiles.append(HookFile(fileName, owner, HookFileType.CURRENT_YEAR, tarFile.extractfile(fileName).read().decode('utf-8'))) #This is a whitelist piece of code which shouldn't return plagiarism if it exists in a students submission elif filePathElements[0] == 'Exclusions': if ext == ".java": javaWhitelist.append(HookFile(fileName, "", None, tarFile.extractfile(fileName).read().decode('utf-8'))) elif ext == ".cpp" or ext == ".c" or ext == ".hpp" or ext == ".h": cWhitelist.append(HookFile(fileName, "", None, tarFile.extractfile(fileName).read().decode('utf-8'))) """ The MOSS paper on Winnowing goes into detail on how the winnowing algorithm work's and why it is necessary to standardize the input. Section 3 of the paper explains the winnowing algorithm while Section 5.2 describes how to use the algorithm for plagiarism detection. The Paper can be found at https://theory.stanford.edu/~aiken/publications/papers/sigmod03.pdf """ #Standardize the files to be processed, this includes removing variable names. cStandardized: List[StandardizedFile] = standardize.standardizeC(cFiles) cStandardizedWhitelist : List[StandardizedFile] = standardize.standardizeC(cWhitelist) javaStandardized: List[StandardizedFile] = standardize.standardizeJava(javaFiles) javaStandardizedWhitelist : List[StandardizedFile] = standardize.standardizeJava(javaWhitelist) #Apply the winnowing algorithm to the standardized files cMatches: List[Match] = winnow.getMatches(cStandardized, cStandardizedWhitelist) javaMatches: List[Match] = winnow.getMatches(javaStandardized, javaStandardizedWhitelist, len(cMatches)) _, tarFilename = os.path.split(filePath) jobId: str = tarFilename.replace('.tar.gz','') allMatches: List[Match] = cMatches allMatches += javaMatches with open(os.path.join(config["DISK"]["RESULT"], "Results", jobId + ".xml"), 'wb') as f: f.write(xmlGenerator.generateResult(allMatches)) processed_file = timeQueue.pop() os.remove(filePath) notified = __sendEmail(emailAddr,jobId) #not sure what the best thing to do here is. . . endtime = time.time() processing_per_file = (endtime-start)/num_files print("Overall processing time for "+processed_file[0]+" files is: "+ str(processing_per_file)) except Exception as e: print(e) try: #Try to release it incase it hasn't been released mutex.release() except: pass try: msg = EmailMessage() msg.set_content("Error processing job with id: "+jobId+" please try submitting again.") msg["Subject"]= "Error With Job!" msg["To"] = emailAddr msg["From"] = config["EMAIL"]["FromAddr"] s = smtplib.SMTP_SSL(config["EMAIL"]["SMTP_Server"], config["EMAIL"]["SMTP_Port"]) s.login(config["EMAIL"]["FromAddr"], config["EMAIL"]["FromPassword"]) s.sendmail(config["EMAIL"]["FromAddr"], emailAddr, msg.as_string()) s.quit() except: pass
def email_alert(subject, body, to): msg = EmailMessage() msg.set_content(body) user = "******" password = ""
def register(): if request.method == 'POST': firstname = request.form.get('firstname') lastname = request.form.get('lastname') username = request.form.get('username') email = request.form.get('email') address = request.form.get('address') state = request.form.get('state') lga = request.form.get('lga') phone = request.form.get('phone') bvn = request.form.get('bvn') unhashed_password = request.form.get('password') usertype = request.form.get('usertype') # check if username exists checkusername = User.query.filter_by(username=username).first() if checkusername: flash( Markup( ' Username already exists. Already have an account?<a href="login.html" style="color: yellow; font-weight: 900;"> Login In</a>' ), 'error') return redirect(url_for('auth.register')) # check if email already exists checkuseremail = User.query.filter_by(email=email).first() if checkuseremail: flash( Markup( ' Email already exists. Already have an account?<a href="login.html" style="color: yellow; font-weight: 500;"> Login In</a>' ), 'error') return redirect(url_for('auth.register')) new_user = User(lastname=lastname, firstname=firstname, username=username, unhashed_password=unhashed_password, email=email, address=address, state=state, lga=lga, phone=phone, bvn=bvn, usertype=usertype) db.session.add(new_user) db.session.commit() # email message msg = EmailMessage() msg['Subject'] = 'Donate A Seed - Confirmation Email' msg['From'] = "*****@*****.**" msg['To'] = email msg.set_content('') msg.add_alternative("""\ <h1 style="color: #000; font-weight: 600; text-align: center;">Confirmation Email for your Application On Donate A Seed</h1> <br> <p style="color: #222; font-weight: 300;">Hi {}, Your email {} was used for applying on <b>Donate A Seed</b> as a <b>{}</b>. <br> <p>your username is : {}</p> We will review your application and send your results to {} <br> Please ignore this email if you did not apply on our platform. </p> <br>For any enquiries reply to this email and we will get back to you as soon as possible. <br><br><br> Regards,<br> Donate A Seed """.format(firstname, email, usertype, username, email), subtype='html') # email sending function ("it sends an email to registered email address") # with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: # smtp.login("email", "password") # smtp.send_message(msg) #flash(' Registered successfully, please check your email ' + email, 'success') #return redirect(url_for('auth.login')) return render_template('register.html')
import smtplib from email.message import EmailMessage import getpass message = EmailMessage() sender = "*****@*****.**" recipient = "*****@*****.**" message['From'] = sender message['To'] = recipient message['Subject'] = 'Greetings from {} to {}!'.format(sender, recipient) message_body = "Hello, My name is Bat-Ochir!" message.set_content(message_body) # Adding the attachments with open('Bat.jpg', 'rb') as ap: message.add_attachment(ap.read(), maintype="image", subtype="jpg", filename="Bat.jpg") try: # you can use 'localhost' instead of smtp.gmail.com if on linux, because it's set automatically # 465 port == SSL, 587 == TSL mail_server = smtplib.SMTP_SSL('smtp.gmail.com', 465) # so we can see what's popping mail_server.set_debuglevel(1) # getpass is here so it won't be echoing the password mail_pass = getpass.getpass("Password: ")
def main(): # DECLARAÇÃO E INICIALIZAÇÃO DE VARIÁVEIS: parser = argparse.ArgumentParser( description='Dados do GMail e URL da categoria') parser.add_argument( '-u', '--url', type=str, metavar='', required=True, help='Link da categoria da OLX (ex: https://sp.olx.com.br/celulares') parser.add_argument('-g', '--gmail', type=str, metavar='', required=True, help='Endereço do GMail') parser.add_argument('-s', '--senha', type=str, metavar='', required=True, help='Senha do GMail') parser.add_argument('-t', '--timesleep', type=int, metavar='', required=True, help='Tempo entre atualizações de lista (em segundos)') parser.add_argument('-p', '--proxy', type=str, metavar='', required=False, help='Utilizar proxy para realizar as requisições') args = parser.parse_args() URL = args.url EMAIL_ADDRESS = args.gmail EMAIL_PASSWORD = args.senha timesleep = args.timesleep proxy = args.proxy if proxy is not None: proxies = {"http": proxy, "https": proxy} headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36' } # DECLARAÇÃO DE FUNÇÕES: def banner(): print( "╔═══════════════════════════════════════════════════════════════════════════════════════════════╗" ) print( "║ ██████╗ ██╗ ██╗ ██╗ ██╗ ██████╗██████╗ █████╗ ██████╗ ██████╗ ███████╗██████╗ ║" ) print( "║ ██╔═══██╗██║ ╚═╝ ██╗██╔╝ ██╔════╝██╔══██╗██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗ ║" ) print( "║ ██║ ██║██║ ███╔╝█████╗██║ ██████╔╝███████║██████╔╝██████╔╝█████╗ ██████╔╝ ║" ) print( "║ ██║ ██║██║ ██╔██╗╚════╝██║ ██╔══██╗██╔══██║██╔═══╝ ██╔═══╝ ██╔══╝ ██╔══██╗ ║" ) print( "║ ╚██████╔╝███████╗ ██╔╝ ██╗ ╚██████╗██║ ██║██║ ██║██║ ██║ ███████╗██║ ██║ ║" ) print( "║ ╚═════╝ ╚══════╝ ╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═╝ ║" ) print( "╚═══════════════════════════════════════════════════════════════════════════════════════════════╝" ) print( "Ferramenta de scraping de categorias da OLX com suporte a notificação de novos anúncios pelo GMail" ) print( "Autor: Yago Lima Lins | [email protected] | https://github.com/yagolimalins/olxcrapper" ) print( "-------------------------------------------------------------------------------------------------\n" ) def screen_clear(): if os.name == 'posix': _ = os.system('clear') else: _ = os.system('cls') def statuscode(): result = makeRequest() statuscodenumber = int(result.status_code) return (statuscodenumber) def webscrap(): result = makeRequest() src = result.content soup = BeautifulSoup( src, 'lxml' ) # Usando o parser do BS4, alternativamente usar: (src, 'lxml') items = soup.find_all('a') lista = [] for item in items: if ("Hoje" and "R$") in item.text: title = item.get('title') price = item.find('p').get_text() URL = item.attrs['href'] lista.append([title, price, URL]) print(price + ' - ' + title) print( "\n-------------------------------------------------------------------------------------------------" ) return (lista) def makeRequest(URL=URL, headers=headers): if proxy is None: result = requests.get(URL, headers=headers) else: result = requests.get(URL, headers=headers, proxies=proxies) return (result) # EXECUÇÃO DO SCRIPT: banner() listaOld = webscrap() print("O item mais recentemente adicionado é: " + listaOld[0][0] + " - " + listaOld[0][1]) time.sleep(timesleep) while True: screen_clear() banner() statuscodenumber = statuscode() if statuscodenumber == 200: listaNew = webscrap() if listaNew[0][2] != listaOld[0][2]: print("O item mais recentemente anunciado é: " + listaNew[0][0] + " - " + listaNew[0][1]) #------------------------ EMAIL ------------------------------- msg = EmailMessage() msg['Subject'] = "[OLXCRAPPER] " + listaNew[0][ 0] + " - " + listaNew[0][1] msg['From'] = EMAIL_ADDRESS msg['To'] = EMAIL_ADDRESS msg.set_content('Link para o anuncio: ' + listaNew[0][2]) with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD) smtp.send_message(msg) #-------------------------------------------------------------- listaOld = listaNew elif listaNew[0][0] == listaOld[0][0]: print("O item mais recentemente anunciado continua sendo: " + listaOld[0][0] + " - " + listaOld[0][1]) else: print("O site retornou código de status: " + str(statuscodenumber)) time.sleep(timesleep)
import smtplib from email.message import EmailMessage email = EmailMessage() ## Creating a object for EmailMessage email['from'] = 'xyz name' ## Person who is sending email['to'] = 'xyz id' ## Whom we are sending email['subject'] = 'xyz subject' ## Subject of email email.set_content("Xyz content of email") ## content of email with smtlib.SMTP(host='smtp.gmail.com', port=587) as smtp: ## sending request to server smtp.ehlo() ## server object smtp.starttls() ## used to send data between server and client smtp.login("email_id", "Password") ## login id and password of gmail smtp.send_message(email) ## Sending email print("email send") ## Printing success message
def send_mail(): for m in range(len(toSend)): server = smtplib.SMTP_SSL('smtp.gmail.com', 465) # server.starttls() # server.login(username, password)------- server.login('*****@*****.**', 'khurram.saeed03360736736') email = EmailMessage() email['From'] = '*****@*****.**' email['To'] = toSend[m] email['Subject'] = subject text = '''Dear ''' + str(toSend_names[m]) + '''\n I would like to introduce our company SAEED NAVEED BROTHERS \n SAEED NAVEED BROTHERS is a Veterinary Instruments, Farrier Tools, Equestrian Products manufacturing and export company in Pakistan.\n (Our catalog is attached; we can also send you our printed catalog)\n A list of product categories includes:\n • Bits, Spurs, Stirrups\n • Equestrian Health Products\n • Veterinary Instruments\n • Farrier Tools\n • Hoof knives, Folding knives, Custom knives\n • Tongs\n • Clinchers, Adjustable Clinchers\n • Hackamores\n • Eggbutt Bits\n • Cheek Mouth Pieces\n • Castration Forceps\n • Hoof Testers\n • Pet Grooming Shears\n • Equestrian Leather Products\n • Riding Gloves & Chaps\n \n If you need any sample to check our quality. We will be happy to send it to you.\n We do Business World Wide, looking forward to doing good business with you.\n \n Best regards\n \n KHURRAM SAEED\n SALES DIRECTOR\n \n SAEED NAVEED BROTHERS LTD\n MANUFACTURER & EXPORTER OF VETERINARY INSTRUMENTS, EQUESTRIAN HARDWARE AND FARRIER TOOLS\n \n Gmail: [email protected]\n Email: [email protected]\n Cell: +92 321 611 6509\n Phone: +92 52 355 4004\n YouTube: https://www.youtube.com/results?search_query=saeed+naveed+brothers\n Instagram: https://www.instagram.com/snb.company.1971/\n Facebook: www.facebook.com/saeednaveedbrothers\n Alibaba: www.snbrothers.trustpass.alibaba.com\n PayPal: www.paypal.me/SaeedAkhtar\n Address: P.O. Box 1322, 11c Nishter Road, SIE, Sialkot-51310 (Pakistan)\n ''' # html = '''<p style='margin-right:0in;margin-left:0in;font-size:15px;font-family:"Calibri", # sans-serif;margin-top:0in;margin-bottom:.0001pt;line-height:107%;margin:0in;'><span # style='font-family:"Calibri",sans-serif;color:black;'>Dear ''' + str(toSend_names[m]) + '''</span></p> # <p style='margin-right:0in;margin-left:0in;font-size:15px;font-family:"Calibri",sans-serif;margin-top:0in;margin-bottom:.0001pt;line-height:107%;margin:0in;text-align:start;'><span style='font-family:"Calibri",sans-serif;color:black;'>I would like to introduce our company </span><strong><span style='font-size:19px;font-family:"Calibri",sans-serif;color:black;'>SAEED NAVEED BROTHERS </span></strong></p> # <p style='margin-right:0in;margin-left:0in;font-size:15px;font-family:"Calibri",sans-serif;margin-top:0in;margin-bottom:.0001pt;line-height:107%;margin:0in;text-align:start;'><span style='font-family:"Calibri Light",sans-serif;color:black;'>SAEED NAVEED BROTHERS is a Veterinary Instruments, Farrier Tools, Equestrian Products manufacturing and export company in Pakistan.</span></p> # <p style='margin-right:0in;margin-left:0in;font-size:15px;font-family:"Calibri",sans-serif;margin-top:0in;margin-bottom:.0001pt;line-height:107%;margin:0in;text-align:start;'><span style='font-size:15px;font-family:"Calibri Light",sans-serif;color:black;'> </span></p> # <p style='margin-right:0in;margin-left:0in;font-size:15px;font-family:"Calibri",sans-serif;margin-top:0in;margin-bottom:.0001pt;line-height:107%;margin:0in;text-align:start;'><span style='font-family:"Calibri Light",sans-serif;color:red;'>(Our catalog is attached; we can also send you our printed catalog)</span></p> # <p style='margin-right:0in;margin-left:0in;font-size:15px;font-family:"Calibri",sans-serif;margin-top:0in;margin-bottom:.0001pt;line-height:107%;margin:0in;text-align:start;'><span style='font-size:15px;font-family:"Calibri Light",sans-serif;color:black;'> </span></p> # <p style='margin-right:0in;margin-left:0in;font-size:15px;font-family:"Calibri",sans-serif;margin-top:0in;margin-bottom:.0001pt;line-height:107%;margin:0in;text-align:start;'><span style='font-family:"Calibri Light",sans-serif;color:black;'>A list of product categories includes:</span></p> # <ul style="margin-bottom:0in;text-align:start;" type="disc"> # <li style='margin-top:0in;margin-right:0in;margin-bottom:8.0pt;margin-left:0in;line-height:normal;font-size:15px;font-family:"Calibri",sans-serif;color:black;'><span style='font-family:"Calibri Light",sans-serif;'>Bits, Spurs, Stirrups</span></li> # <li style='margin-top:0in;margin-right:0in;margin-bottom:8.0pt;margin-left:0in;line-height:normal;font-size:15px;font-family:"Calibri",sans-serif;color:black;'><span style='font-family:"Calibri Light",sans-serif;'>Equestrian Health Products</span></li> # <li style='margin-top:0in;margin-right:0in;margin-bottom:8.0pt;margin-left:0in;line-height:normal;font-size:15px;font-family:"Calibri",sans-serif;color:black;'><span style='font-family:"Calibri Light",sans-serif;'>Veterinary Instruments</span></li> # <li style='margin-top:0in;margin-right:0in;margin-bottom:8.0pt;margin-left:0in;line-height:normal;font-size:15px;font-family:"Calibri",sans-serif;color:black;'><span style='font-family:"Calibri Light",sans-serif;'>Farrier Tools</span></li> # <li style='margin-top:0in;margin-right:0in;margin-bottom:8.0pt;margin-left:0in;line-height:normal;font-size:15px;font-family:"Calibri",sans-serif;color:black;'><span style='font-family:"Calibri Light",sans-serif;'>Hoof knives, Folding knives, Custom knives</span></li> # <li style='margin-top:0in;margin-right:0in;margin-bottom:8.0pt;margin-left:0in;line-height:normal;font-size:15px;font-family:"Calibri",sans-serif;color:black;'><span style='font-family:"Calibri Light",sans-serif;'>Tongs</span></li> # <li style='margin-top:0in;margin-right:0in;margin-bottom:8.0pt;margin-left:0in;line-height:normal;font-size:15px;font-family:"Calibri",sans-serif;color:black;'><span style='font-family:"Calibri Light",sans-serif;'>Clinchers, Adjustable Clinchers</span></li> # <li style='margin-top:0in;margin-right:0in;margin-bottom:8.0pt;margin-left:0in;line-height:normal;font-size:15px;font-family:"Calibri",sans-serif;color:black;'><span style='font-family:"Calibri Light",sans-serif;'>Hackamores</span></li> # <li style='margin-top:0in;margin-right:0in;margin-bottom:8.0pt;margin-left:0in;line-height:normal;font-size:15px;font-family:"Calibri",sans-serif;color:black;'><span style='font-family:"Calibri Light",sans-serif;'>Eggbutt Bits</span></li> # <li style='margin-top:0in;margin-right:0in;margin-bottom:8.0pt;margin-left:0in;line-height:normal;font-size:15px;font-family:"Calibri",sans-serif;color:black;'><span style='font-family:"Calibri Light",sans-serif;'>Cheek Mouth Pieces </span></li> # <li style='margin-top:0in;margin-right:0in;margin-bottom:8.0pt;margin-left:0in;line-height:normal;font-size:15px;font-family:"Calibri",sans-serif;color:black;'><span style='font-family:"Calibri Light",sans-serif;'>Castration Forceps</span></li> # <li style='margin-top:0in;margin-right:0in;margin-bottom:8.0pt;margin-left:0in;line-height:normal;font-size:15px;font-family:"Calibri",sans-serif;color:black;'><span style='font-family:"Calibri Light",sans-serif;'>Hoof Testers</span></li> # <li style='margin-top:0in;margin-right:0in;margin-bottom:8.0pt;margin-left:0in;line-height:normal;font-size:15px;font-family:"Calibri",sans-serif;color:black;'><span style='font-family:"Calibri Light",sans-serif;'>Pet Grooming Shears</span></li> # <li style='margin-top:0in;margin-right:0in;margin-bottom:8.0pt;margin-left:0in;line-height:normal;font-size:15px;font-family:"Calibri",sans-serif;color:black;'><span style='font-family:"Calibri Light",sans-serif;'>Equestrian Leather Products</span></li> # <li style='margin-top:0in;margin-right:0in;margin-bottom:8.0pt;margin-left:0in;line-height:normal;font-size:15px;font-family:"Calibri",sans-serif;color:black;'><span style='font-family:"Calibri Light",sans-serif;'>Riding Gloves & Chaps</span></li> # </ul> # <p style='margin-right:0in;margin-left:0in;font-size:15px;font-family:"Calibri",sans-serif;margin-top:0in;margin-bottom:.0001pt;line-height:107%;margin:0in;text-align:start;'><span style='font-family:"Calibri Light",sans-serif;color:black;'> </span></p> # <p style='margin-right:0in;margin-left:0in;font-size:15px;font-family:"Calibri",sans-serif;margin-top:0in;margin-bottom:.0001pt;line-height:107%;margin:0in;text-align:start;'><span style='font-family:"Calibri Light",sans-serif;color:black;'>If you need any sample to check our quality. We will be happy to send it to you.</span></p> # <p style='margin-right:0in;margin-left:0in;font-size:15px;font-family:"Calibri",sans-serif;margin-top:0in;margin-bottom:.0001pt;line-height:107%;margin:0in;text-align:start;'><span style='font-size:15px;font-family:"Calibri Light",sans-serif;color:black;'>We do Business World Wide, </span><span style='font-family:"Calibri Light",sans-serif;color:black;'>looking forward to doing good business with you.</span></p> # <p style='margin-right:0in;margin-left:0in;font-size:15px;font-family:"Calibri",sans-serif;margin-top:0in;margin-bottom:.0001pt;line-height:107%;margin:0in;text-align:start;'><span style='font-size:15px;font-family:"Calibri Light",sans-serif;color:black;'> </span></p> # <p style='margin-right:0in;margin-left:0in;font-size:15px;font-family:"Calibri",sans-serif;margin-top:0in;margin-bottom:.0001pt;line-height:107%;margin:0in;text-align:start;'><span style='font-family:"Calibri Light",sans-serif;color:black;'>Best regards</span></p> # <p style='margin-right:0in;margin-left:0in;font-size:15px;font-family:"Calibri",sans-serif;margin-top:0in;margin-bottom:.0001pt;line-height:107%;margin:0in;text-align:start;'><span style='font-size:15px;font-family:"Garamond",serif;color:#500050;'><br> KHURRAM SAEED</span></p> # <p style='margin-right:0in;margin-left:0in;font-size:15px;font-family:"Calibri",sans-serif;margin-top:0in;margin-bottom:.0001pt;line-height:107%;margin:0in;background:white;text-align:start;'><span style='font-size:13px;font-family:"Garamond",serif;color:#500050;'>SALES DIRECTOR</span></p> # <p style='margin-right:0in;margin-left:0in;font-size:15px;font-family:"Calibri",sans-serif;margin-top:0in;margin-bottom:.0001pt;line-height:107%;margin:0in;background:white;text-align:start;'><span style='font-size:13px;font-family:"Arial",sans-serif;color:#500050;'> </span></p> # <p style='margin-right:0in;margin-left:0in;font-size:15px;font-family:"Calibri",sans-serif;margin-top:0in;margin-bottom:.0001pt;line-height:107%;margin:0in;background:white;text-align:start;'><span style='font-size:27px;font-family:"Garamond",serif;color:#444444;'>SAEED NAVEED BROTHERS </span><span style='font-size:15px;font-family:"Garamond",serif;color:#444444;'>LTD</span></p> # <p style='margin-right:0in;margin-left:0in;font-size:15px;font-family:"Calibri",sans-serif;margin-top:0in;margin-bottom:.0001pt;line-height:107%;margin:0in;background:white;text-align:start;'><span style='font-size:13px;font-family:"Garamond",serif;color:#666666;'>MANUFACTURER & EXPORTER OF VETERINARY INSTRUMENTS, EQUESTRIAN HARDWARE AND FARRIER TOOLS</span></p> # <p style='margin-right:0in;margin-left:0in;font-size:15px;font-family:"Calibri",sans-serif;margin-top:0in;margin-bottom:.0001pt;line-height:107%;margin:0in;background:white;text-align:start;'><span style='font-size:13px;font-family:"Arial",sans-serif;color:#500050;'> </span></p> # <p style='margin-right:0in;margin-left:0in;font-size:15px;font-family:"Calibri",sans-serif;margin-top:0in;margin-bottom:.0001pt;line-height:107%;margin:0in;background:white;text-align:start;'><span style='font-size:15px;font-family:"Courier New";color:#666666;'>Gmail: </span><u><span style='font-size:15px;font-family:"Courier New";color:#1155CC;'><a href="mailto:[email protected]" target="_blank"><span style="color:#1155CC;">[email protected]</span></a></span></u></p> # <p style='margin-right:0in;margin-left:0in;font-size:15px;font-family:"Calibri",sans-serif;margin-top:0in;margin-bottom:.0001pt;line-height:107%;margin:0in;background:white;text-align:start;'><span style='font-size:15px;font-family:"Courier New";color:#666666;'>Email: </span><u><span style='font-size:15px;font-family:"Courier New";color:#1155CC;'><a href="mailto:[email protected]" target="_blank"><span style="color:#1155CC;">[email protected]</span></a></span></u><span style='font-size:15px;font-family:"Courier New";color:#666666;'> <br>Cell: +92 321 611 6509</span></p> # <p style='margin-right:0in;margin-left:0in;font-size:15px;font-family:"Calibri",sans-serif;margin-top:0in;margin-bottom:.0001pt;line-height:107%;margin:0in;background:white;text-align:start;'><span style='font-size:15px;font-family:"Courier New";color:#666666;'>Phone: +92 52 355 4004</span></p> # <p style='margin-right:0in;margin-left:0in;font-size:15px;font-family:"Calibri",sans-serif;margin-top:0in;margin-bottom:.0001pt;line-height:107%;margin:0in;background:white;text-align:start;'><span style='font-size:15px;font-family:"Courier New";color:#666666;'>YouTube: </span><u><span style='font-size:15px;font-family:"Courier New";color:blue;'><a href="https://www.youtube.com/results?search_query=saeed+naveed+brothers">https://www.youtube.com/results?search_query=saeed+naveed+brothers</a></span></u></p> # <p style='margin-right:0in;margin-left:0in;font-size:15px;font-family:"Calibri",sans-serif;margin-top:0in;margin-bottom:.0001pt;line-height:107%;margin:0in;background:white;text-align:start;'><span style='font-size:15px;font-family:"Courier New";color:#767171;'>Instagram: </span><u><span style='font-size:15px;font-family:"Courier New";color:blue;'><a href="https://www.instagram.com/snb.company.1971/">https://www.instagram.com/snb.company.1971/</a></span></u><u><span style='font-size:21px;font-family:"Courier New";color:#666666;'><br></span></u><span style='font-size:15px;font-family:"Courier New";color:#666666;'>Facebook: </span><u><span style='font-size:15px;font-family:"Courier New";color:#1155CC;'><a href="http://www.facebook.com/saeednaveedbrothers" target="_blank"><span style="color:#1155CC;">www.facebook.com/saeednaveedbrothers</span></a></span></u><span style='font-size:15px;font-family:"Courier New";color:#666666;'><br>Alibaba: </span><u><span style='font-size:15px;font-family:"Courier New";color:#1155CC;'><a href="http://www.snbrothers.trustpass.alibaba.com/" target="_blank"><span style="color:#1155CC;">www.snbrothers.trustpass.alibaba.com</span></a></span></u><span style='font-size:15px;font-family:"Courier New";color:#666666;'><br>PayPal: </span><u><span style='font-size:15px;font-family:"Courier New";color:#1155CC;'><a href="http://www.paypal.me/SaeedAkhtar" target="_blank"><span style="color:#1155CC;">www.paypal.me/SaeedAkhtar</span></a></span></u></p> # <p style='margin-right:0in;margin-left:0in;font-size:15px;font-family:"Calibri",sans-serif;margin-top:0in;margin-bottom:.0001pt;line-height:107%;margin:0in;background:white;text-align:start;'><span style='font-size:15px;font-family:"Courier New";color:#666666;'>Address: P.O. Box 1322, 11c Nishter Road, SIE, Sialkot-51310 (Pakistan)</span></p>''' # part1=MIMEText(text,'plain') # part2=MIMEText(html,'html') # msg.attach(part1) # msg.attach(part2) email.set_content(text) # Attaching pdf # with open('D://raima//Desktop//Business//snb-main.pdf', 'rb') as f: # file_data = f.read() # file_name = 'SNB Main Catalog' # email.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name) # # with open('D://raima//Desktop//Business//snb-vet.pdf', 'rb') as f: # file_data = f.read() # file_name = 'SNB Veterinary Catalog' # email.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name) # # with open('D://raima//Desktop//Business//banner.jpg', 'rb') as image: # image_data = image.read() # image_type = imghdr.what(image.name) # image_name = 'SNB Banner' # email.add_attachment(image_data, maintype='image', subtype=image_type, filename=image_name) server.send_message(email) print(str(m + 1) + '. sent to ' + str(toSend[m])) time.sleep(30)
def _get_dehydrated_message(self, msg, record): settings = utils.get_settings() new = EmailMessage() if msg.is_multipart(): for header, value in msg.items(): new[header] = value for part in msg.get_payload(): new.attach( self._get_dehydrated_message(part, record) ) elif ( settings['strip_unallowed_mimetypes'] and not msg.get_content_type() in settings['allowed_mimetypes'] ): for header, value in msg.items(): new[header] = value # Delete header, otherwise when attempting to deserialize the # payload, it will be expecting a body for this. del new['Content-Transfer-Encoding'] new[settings['altered_message_header']] = ( 'Stripped; Content type %s not allowed' % ( msg.get_content_type() ) ) new.set_payload('') elif ( ( msg.get_content_type() not in settings['text_stored_mimetypes'] ) or ('attachment' in msg.get('Content-Disposition', '')) ): filename = None raw_filename = msg.get_filename() if raw_filename: filename = utils.convert_header_to_unicode(raw_filename) if not filename: extension = mimetypes.guess_extension(msg.get_content_type()) else: _, extension = os.path.splitext(filename) if not extension: extension = '.bin' attachment = MessageAttachment() attachment.document.save( uuid.uuid4().hex + extension, ContentFile( six.BytesIO( msg.get_payload(decode=True) ).getvalue() ) ) attachment.message = record for key, value in msg.items(): attachment[key] = value attachment.save() placeholder = EmailMessage() placeholder[ settings['attachment_interpolation_header'] ] = str(attachment.pk) new = placeholder else: content_charset = msg.get_content_charset() if not content_charset: content_charset = 'ascii' try: # Make sure that the payload can be properly decoded in the # defined charset, if it can't, let's mash some things # inside the payload :-\ msg.get_payload(decode=True).decode(content_charset) except LookupError: logger.warning( "Unknown encoding %s; interpreting as ASCII!", content_charset ) msg.set_payload( msg.get_payload(decode=True).decode( 'ascii', 'ignore' ) ) except ValueError: logger.warning( "Decoding error encountered; interpreting %s as ASCII!", content_charset ) msg.set_payload( msg.get_payload(decode=True).decode( 'ascii', 'ignore' ) ) new = msg return new
# grab session info from calendar invite files and make emails with # attachments. for file_name in session_files: # get id from session file name id = int(re.match(r'sess(\d\d\d).ics', file_name).group(1)) # chair name and email from session id name, email = chairs[id] # open the calendar file and read it in with open(file_name) as f: ics_file = f.read() f.seek(0) event = Calendar(f.read()).events[0] m = EmailMessage() m['From'] = 'Todd Gamblin <*****@*****.**>' m['To'] = '%s <%s>' % (name, email) m['Cc'] = 'Torsten Hoefler <*****@*****.**>' m['Subject'] = f'Session Chair for {event.name} at SC18' body = m.set_content(f'''\ Dear {name}, Thanks for agreeing to be a session chair at SC18! Session chairs help to ensure that SC technical talks run smoothly, and they help to provide lively and engaging technical discussion after presentations. You are scheduled to chair paper session {id} at SC18: Title: {event.name}