def email_user(data, timestamp, user_email): print("emailing") # using yagmail. uses keyring for sender data yag = SMTP() contents = "" with open('ghostEmail.html', 'r') as contentsFile: contents = contentsFile.read() contents += '''<body> <center> <h1> Your Spook-O-Matic 2000 has detected a ghost!</h1> <hr> <h4> The haunting was ''' + str(data) + '''mv </h4> <hr> <h4> The detection was at ''' + timestamp + '''</h4> <hr> <h4> Cheers, <br> The Spook-O-Matic 2000 team </h4> </center> </body> </html>''' yag.send(user_email, "Critical Ghost Levels Detected!", contents)
class EmailAPI(Resource): def __init__(self): parser = reqparse.RequestParser() parser.add_argument('from', type=str, required=True, help='No `from` supplied.', location='json') parser.add_argument('subject', type=str, required=True, help='No `subject` supplied.', location='json') parser.add_argument('content', type=str, required=True, help='No `content` supplied.', location='json') self.parser = parser self.yag = SMTP('YOUR_EMAIL_HERE', oauth2_file="./credentials.json") # @jwt_required def post(self): # Gets the supplied args args = self.parser.parse_args() log('got arguments: {}'.format(args)) _from = args.get('from') subject = args.get('subject') content = args.get('content') contents = 'From: {}. \n Content: {}'.format(_from, content) self.yag.send( subject=subject, contents=contents ) return { 'from': _from, 'subject': subject, 'content': content }
def send_email(rost_df): """Sends an email with the latest highly-rostered free agent.""" recipient = credentials.recipient sender = credentials.sender subject = 'ESPN Free Agent Alert' body = rost_df.to_dict(orient='index') yag = SMTP(sender, oauth2_file="./oauth2_creds.json") yag.send(to=recipient, subject=subject, contents=body)
def send_message(): SENDER_EMAIL = os.getenv("SENDER_EMAIL") RECIPIENT_EMAIL = os.getenv("RECIPIENT_EMAIL") yag = SMTP(SENDER_EMAIL, oauth2_file="oauth2_creds.json") body = "{} There are new polls available at: https://projects.fivethirtyeight.com/polls/".format( datetime.now()) yag.send(to=RECIPIENT_EMAIL, subject="New Poll", contents=body)
def __init__(self): parser = reqparse.RequestParser() parser.add_argument('from', type=str, required=True, help='No `from` supplied.', location='json') parser.add_argument('subject', type=str, required=True, help='No `subject` supplied.', location='json') parser.add_argument('content', type=str, required=True, help='No `content` supplied.', location='json') self.parser = parser self.yag = SMTP('YOUR_EMAIL_HERE', oauth2_file="./credentials.json")
def send_email(smtp_client: SMTP, subject: str, contents: str, attachments: List[str], to: str = MAIN_EMAIL) -> None: smtp_client.send(to=to, subject=subject, contents=contents, attachments=attachments)
def _test_email_with_dkim(include_headers): from yagmail import SMTP from yagmail.dkim import DKIM private_key_path = Path(__file__).parent / "privkey.pem" private_key = private_key_path.read_bytes() dkim_obj = DKIM( domain=b"a.com", selector=b"selector", private_key=private_key, include_headers=include_headers, ) yag = SMTP( user="******", host="smtp.blabla.com", port=25, dkim=dkim_obj, ) yag.login = Mock() to = "*****@*****.**" recipients, msg_bytes = yag.send(to=to, subject="hello from tests", contents="important message", preview_only=True) msg_string = msg_bytes.decode("utf8") assert recipients == [to] assert "Subject: hello from tests" in msg_string text_b64 = base64.b64encode(b"important message").decode("utf8") assert text_b64 in msg_string dkim_string1 = "DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=a.com; [email protected];\n " \ "q=dns/txt; s=selector; t=" assert dkim_string1 in msg_string l = logging.getLogger() l.setLevel(level=logging.DEBUG) logging.basicConfig(level=logging.DEBUG) assert dkim.verify(message=msg_string.encode("utf8"), logger=l, dnsfunc=get_txt_from_test_file) return msg_string
class Mailman(object): account = "*****@*****.**" password = "******" subject = "Research Scraper registration Invitation" def __init__(self): #https://stackoverflow.com/questions/26852128/smtpauthenticationerror-when-sending-mail-using-gmail-and-python self.sender = SMTP(self.account, self.password) def send_invitation(self, email, name, author_id): with open('web/mailman/content.txt') as f: raw_content = f.read() content = raw_content % (name, session['name'], author_id) self.sender.send(email, self.subject, content)
def query(): available = False output = [] gmail_user = os.environ.get('GMAIL_USER') gmail_password = os.environ.get('GMAIL_PASSWORD') for item_name, item_id in items_wanted.items(): availability_data = get(availability_url.format(region=region, locale=locale, item_id=item_id)) for city, code in local_stores.items(): available_qty = int(ElementTree.fromstring(availability_data.content) .find(".//localStore[@buCode='{code}']".format(code=code)) .find('.//availableStock').text) if available_qty > 0: available = True message = "{} available {} ({}) {} @ {}".format( available_qty, item_name, item_id, city, datetime.now()) output.append(message) print(message) if available and gmail_user and gmail_password: SMTP(gmail_user, gmail_password).send(to=gmail_user, subject='Ikea Availability', contents='\n'.join(output)) else: print('No items available @ {}'.format(datetime.now()))
def button_trigger(mode): global ERROR_LOG, progress_var try: wb = open_workbook(EXCEL) sheet = wb.sheet_by_index(0) progress_var.set(0) cmsgvar.set('Completed 0/%d' % (int(sheet.nrows))) if (mode == 2) and not check_internet(): tkMessageBox.showwarning( 'No Internet Connection', 'Please check your internet connection and retry.') return else: global yag yag = SMTP(FROM_EMAIL, FROM_EMAIL_PASSWORD) generate(mode) except Exception as err: ERROR_LOG += '>>> ' + str(err) + '\n\n' tkMessageBox.showwarning( 'Unexpected Error Occured', ERROR_LOG + 'Please report the error(s) to [email protected]')
def yagmail(self): #如果有开启邮件服务 ''' Mail_username = self.Mail_user.text() Mail_passwd = self.Mail_passwd.text() Server_host = self.Server_host.text() Server_port = self.Server_port.text() #Mail_list = [Mail_username, Mail_passwd, Server_host, Server_port] ''' # 链接邮箱服务器 yag = SMTP(user=self.username, password=self.pwd, host=self.host, port=self.port) # 发送邮件 yag.send( to=self. username, # 如果多个收件人的话,写成list就行了,如果只是一个账号,就直接写字符串就行to='*****@*****.**' #cc='*****@*****.**', # 抄送 subject='for_test', # 邮件标题 contents=self.content, # 邮件正文 #attachments=[r'd://log.txt', r'd://baidu_img.jpg'] # 附件如果只有一个的话,用字符串就行,attachments=r'd://baidu_img.jpg' ) #可简写成: #yag.send('*****@*****.**', '发送附件', contents, ["d://log.txt", "d://baidu_img.jpg"]) # 关闭 yag.close()
class EmailCoreService: def __init__(self): self._db = SessionLocal() self._jinja_env = Environment(loader=FileSystemLoader( searchpath="src/templates")) self._yag = SMTP(settings.EMAIL_FROM, oauth2_file=settings.GMAIL_CREDENTIALS_PATH) def add_message_to_queue(self, to: str, subject_template_path: str, html_template_path: str, environment: Any): subject = self._jinja_env.get_template(subject_template_path).render( environment) html = self._jinja_env.get_template(html_template_path).render( environment) self._db.add( MessageQueue(to=to, subject=subject, contents=html, status=MessageStatus.NEW, message="")) self._db.commit() def send_message_from_queue(self) -> bool: """Find a new message in the queue and send it. Returns False if queue is empty """ message: MessageQueue = self._db.query(MessageQueue) \ .filter(MessageQueue.status == MessageStatus.NEW) \ .with_for_update(skip_locked=True, key_share=True) \ .first() if not message: return False try: self.send_message(message.to, message.subject, message.contents) # TODO: Handle errors finally: message.status = MessageStatus.OK self._db.commit() return True def send_message(self, to: str, subject: str, contents: str, html=True): if html: contents = contents.replace( "\n", " ") # Prevent yagmail from replacing newlines with <br> tags return self._yag.send(to, subject, contents)
def send_mails(emitter, password, contacts, content): yag = SMTP(emitter, password) phr = content['Phrase'] des = content['Definition'] exa = content['Example'] body = 'Phrase: {}\nDefinition: {}\nExample: {}'.format(phr, des, exa) for name, reciever in zip(contacts['Names'], contacts['Mails']): yag.send( to=reciever, subject="Hola {}, esta es la frase de hoy".format(name), contents=body, ) yag.close()
def yagmail_test(self): # 链接邮箱服务器 yag = SMTP(user=self.username, password=self.pwd, host=self.host, port=self.port) # 发送邮件 yag.send(to=self.username, subject='for_test', contents='test for script') #yag.send('*****@*****.**', '发送附件', contents, ["d://log.txt", "d://baidu_img.jpg"]) # 关闭 yag.close()
def exithandler(): #Change email accordingly yag = SMTP({"@gmail.com": "Darkstar"}, "") yag.send("@live.com", "Error", "Posting Stopped")
def send_email(yag_sender: yagmail.SMTP, recipient_emails: List[str], *args, **kwargs): for i in range(len(recipient_emails)): current_recipient = recipient_emails[i] yag_sender.send(current_recipient, *args, **kwargs)
import itertools import sys from os import path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) from yagmail import SMTP yag = SMTP() def getCombinations(): tos = (None, (yag.user), [yag.user, yag.user], { yag.user: '******', yag.user + '1': 'me' }) subjects = ('subj', ['subj'], ['subj', 'subj1']) contents = (None, ['body'], [ 'body', 'body1', '<h2><center>Text</center></h2>', 'http://github.com/kootenpv/yagmail', 'body', 'http://tinyurl.com/nwe5hxj' ]) results = [] for x in itertools.product(tos, subjects, contents): options = {y: z for y, z in zip(['to', 'subject', 'contents'], x)} options['preview_only'] = True options['use_cache'] = True results.append(options) return results
import itertools import sys from os import path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) from yagmail import SMTP yag = SMTP("py.test", "py.test") def getCombinations(): tos = (None, (yag.user), [yag.user, yag.user], { yag.user: '******', yag.user + '1': 'me' }) subjects = ('subj', ['subj'], ['subj', 'subj1']) contents = (None, ['body'], ['body', 'body1', '<h2><center>Text</center></h2>']) results = [] for x in itertools.product(tos, subjects, contents): options = {y: z for y, z in zip(['to', 'subject', 'contents'], x)} options['preview_only'] = True options['use_cache'] = True results.append(options) return results def test_one(): mail_combinations = getCombinations() for combination in mail_combinations:
from yagmail import SMTP yag = SMTP('YOUR_EMAIL_HERE', oauth2_file="./credentials.json")
def __init__(self): self._db = SessionLocal() self._jinja_env = Environment(loader=FileSystemLoader( searchpath="src/templates")) self._yag = SMTP(settings.EMAIL_FROM, oauth2_file=settings.GMAIL_CREDENTIALS_PATH)
def test_one(): """ Tests several versions of allowed input for yagamail """ yag = SMTP("py.test", "py.test") mail_combinations = get_combinations(yag) for combination in mail_combinations: print(yag.send(**combination))
def __init__(self): #https://stackoverflow.com/questions/26852128/smtpauthenticationerror-when-sending-mail-using-gmail-and-python self.sender = SMTP(self.account, self.password)
def test_one(): """ Tests several versions of allowed input for yagamail """ yag = SMTP(smtp_skip_login=True) mail_combinations = get_combinations(yag) for combination in mail_combinations: print(yag.send(**combination))
def smtp(self): if self._smtp is None: from yagmail import SMTP self.set_credentials() self._smtp = SMTP(self.email, **self._kwargs) return self._smtp