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 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 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)
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 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 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()
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 _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 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 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 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)
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))