def _mail_recipient(recipient_name, recipient_email, sender_name, sender_url, subject, body, headers={}): mail_from = config.get('ckan.mail_from') body = add_msg_niceties(recipient_name, body, sender_name, sender_url) msg = MIMEText(body.encode('utf-8'), 'plain', 'utf-8') for k, v in headers.items(): msg[k] = v subject = Header(subject.encode('utf-8'), 'utf-8') msg['Subject'] = subject msg['From'] = _("%s <%s>") % (sender_name, mail_from) recipient = u"%s <%s>" % (recipient_name, recipient_email) msg['To'] = Header(recipient, 'utf-8') msg['Date'] = Utils.formatdate(time()) msg['X-Mailer'] = "CKAN %s" % __version__ try: server = smtplib.SMTP( config.get('test_smtp_server', config.get('smtp_server', 'localhost'))) #server.set_debuglevel(1) server.sendmail(mail_from, [recipient_email], msg.as_string()) server.quit() except Exception, e: msg = '%r' % e log.exception(msg) raise MailerException(msg)
def mimemelding(self): m = MIMEMultipart() m['Subject'] = Header(self.tittel, self.charset) n = self.ordre.firma.firmanavn.replace(';', ' ').replace(',',' ') m['From'] = '"%s" <%s>' % (Header(n, self.charset), self.fra) #m['To'] = '"%s" <%s>' % (Header(self.ordre.kunde.navn, self.charset), self.til) m['To'] = self.til #'"%s" <%s>' % (Header(self.ordre.kunde.navn, self.charset), self.til) m.preamble = 'You will not see this in a MIME-aware mail reader.\n' # To guarantee the message ends with a newline m.epilogue = '' # Legg til tekstlig informasjon t = MIMEText(self.tekst.encode(self.charset), 'plain', self.charset) m.attach(t) # Legg til fakturaen b = MIMEBase('application', 'x-pdf') _filename=Header('%s-%i.pdf' % (self.ordre.firma.firmanavn, self.ordre.ID), self.charset) b.add_header('Content-Disposition', 'attachment', filename=_filename.encode()) # legg til filnavn m.attach(b) fp = open(self.pdfFilnavn, 'rb') b.set_payload(fp.read()) # les inn fakturaen fp.close() encoders.encode_base64(b) #base64 encode subpart # Legg til vedlegg for filnavn, vedlegg in self.vedlegg: v = MIMEBase('application', 'octet-stream') _filename=Header(filnavn, self.charset) v.add_header('Content-Disposition', 'attachment', filename=_filename.encode()) # legg til filnavn m.attach(v) v.set_payload(vedlegg) encoders.encode_base64(v) #base64 encode subpart return m
def to_mail(to_name, to_email, subject, body, headers={}, decorate_body=True): try: email_from = config.get("adhocracy.email.from") if decorate_body: body = ( _(u"Hi %s,") % to_name + u"\r\n\r\n%s\r\n\r\n" % body + _(u"Cheers,\r\n\r\n" u" the %s Team\r\n") % config.get("adhocracy.site.name") ) msg = MIMEText(body.encode(ENCODING), "plain", ENCODING) for k, v in headers.items(): msg[k] = v subject = Header(subject.encode(ENCODING), ENCODING) msg["Subject"] = subject msg["From"] = _("%s <%s>") % (config.get("adhocracy.site.name"), email_from) to = Header(u"%s <%s>" % (to_name, to_email), ENCODING) msg["To"] = to msg["Date"] = email.Utils.formatdate(time()) msg["X-Mailer"] = "Adhocracy SMTP %s" % version.get_version() # log.debug("MAIL\r\n" + msg.as_string()) send(email_from, to_email, msg.as_string()) except Exception: log.exception("Sending mail failed.")
def _mail_recipient(recipient_name, recipient_email, sender_name, sender_url, subject, body, headers={}): mail_from = config.get('smtp.mail_from') body = add_msg_niceties(recipient_name, body, sender_name, sender_url) msg = MIMEText(body.encode('utf-8'), 'plain', 'utf-8') for k, v in headers.items(): msg[k] = v subject = Header(subject.encode('utf-8'), 'utf-8') msg['Subject'] = subject msg['From'] = _("%s <%s>") % (sender_name, mail_from) recipient = u"%s <%s>" % (recipient_name, recipient_email) msg['To'] = Header(recipient, 'utf-8') msg['Date'] = Utils.formatdate(time()) msg['X-Mailer'] = "CKAN %s" % ckan.__version__ # Send the email using Python's smtplib. smtp_connection = smtplib.SMTP() if 'smtp.test_server' in config: # If 'smtp.test_server' is configured we assume we're running tests, # and don't use the smtp.server, starttls, user, password etc. options. smtp_server = config['smtp.test_server'] smtp_starttls = False smtp_user = None smtp_password = None else: smtp_server = config.get('smtp.server', 'localhost') smtp_starttls = paste.deploy.converters.asbool( config.get('smtp.starttls')) smtp_user = config.get('smtp.user') smtp_password = config.get('smtp.password') smtp_connection.connect(smtp_server) try: #smtp_connection.set_debuglevel(True) # Identify ourselves and prompt the server for supported features. smtp_connection.ehlo() # If 'smtp.starttls' is on in CKAN config, try to put the SMTP # connection into TLS mode. if smtp_starttls: if smtp_connection.has_extn('STARTTLS'): smtp_connection.starttls() # Re-identify ourselves over TLS connection. smtp_connection.ehlo() else: raise MailerException("SMTP server does not support STARTTLS") # If 'smtp.user' is in CKAN config, try to login to SMTP server. if smtp_user: assert smtp_password, ("If smtp.user is configured then " "smtp.password must be configured as well.") smtp_connection.login(smtp_user, smtp_password) smtp_connection.sendmail(mail_from, [recipient_email], msg.as_string()) log.info("Sent email to {0}".format(recipient_email)) except smtplib.SMTPException, e: msg = '%r' % e log.exception(msg) raise MailerException(msg)
def encode_header(key, value): """ encodes a unicode string as a valid header value :param key: the header field this value will be stored in :type key: str :param value: the value to be encoded :type value: unicode """ # handle list of "realname <email>" entries separately if key.lower() in ['from', 'to', 'cc', 'bcc']: rawentries = value.split(',') encodedentries = [] for entry in rawentries: m = re.search('\s*(.*)\s+<(.*\@.*\.\w*)>\s*$', entry) if m: # If a realname part is contained name, address = m.groups() # try to encode as ascii, if that fails, revert to utf-8 # name must be a unicode string here namepart = Header(name) # append address part encoded as ascii entry = '%s <%s>' % (namepart.encode(), address) encodedentries.append(entry) value = Header(', '.join(encodedentries)) else: value = Header(value) return value
def _write_headers(self, msg): # This is almost the same as the string version, except for handling # strings with 8bit bytes. for h, v in msg._headers: self.write('%s: ' % h) if isinstance(v, str): if _has_surrogates(v): if not self.policy.must_be_7bit: # If we have raw 8bit data in a byte string, we have no idea # what the encoding is. There is no safe way to split this # string. If it's ascii-subset, then we could do a normal # ascii split, but if it's multibyte then we could break the # string. There's no way to know so the least harm seems to # be to not split the string and risk it being too long. self.write(v+NL) continue h = Header(v, charset=_charset.UNKNOWN8BIT, header_name=h) else: h = Header(v, header_name=h) else: # Assume it is a Header-like object. h = v self.write(h.encode(linesep=self._NL, maxlinelen=self._maxheaderlen)+self._NL) # A blank line always separates headers from body self.write(self._NL)
def encode_param(key, name, value): try: value = value.encode("ascii") return email.message._formatparam(name, value) except Exception: value = Header(value.encode("utf-8"), "utf-8", header_name=key).encode(splitchars=' ;,') return email.message._formatparam(name, value)
def send_mail(self, title, content=None, files=None): me = Header(self.config.nick_name, 'utf-8') me.append("<" + self.config.mail_user + "@" + self.config.mail_postfix + ">", 'ascii') #创建一个带附件的实例 msg = MIMEMultipart() #msg = MIMEText(content, _subtype='plain', _charset='gb2312') msg['Subject'] = title msg['From'] = me msg['To'] = ";".join(self.config.mailto_list) try: text = MIMEText(content, 'plain', 'utf-8') msg.attach(text) if files!=None: for file in files: att = MIMEText(open(file, 'rb').read(), 'base64', 'utf-8') att["Content-Type"] = 'application/octet-stream' att["Content-Disposition"] = 'attachment; filename="'+file+'.txt"' msg.attach(att) server = smtplib.SMTP() server.connect(self.config.mail_host) server.login(self.config.mail_user, self.config.mail_pass) print("email sending ....") t1 = time.clock() server.sendmail(self.config.mail_from, self.config.mailto_list, msg.as_string()) t2 = time.clock() server.close() t3 = t2 - t1 print('success send email ', title, " takes time ", t3) return True except Exception as e: print('failed send email:', e) return False
def sendmail(to_list,host,me,subject,files,content,sysbl): logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='/home/qa/scripts/sendReport/goldpay/GoldpayReportSendmail.log', filemode='a+') mail_list = to_list.split(';') for i in mail_list: msg = MIMEMultipart() h = Header('Goldpay') h.append('<'+me+'>') msg['From'] = h msg['To'] = i msg['Subject'] = subject msg['Date'] = formatdate(localtime=True) msg.attach(MIMEText(content,'html','utf8')) part = MIMEBase('application', 'octet-stream') part.set_payload(open(files, 'rb').read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(files)) msg.attach(part) smtp = smtplib.SMTP(host) smtp.set_debuglevel(1) try: smtp.sendmail(me,i,msg.as_string()) logging.info('%s %s email send success.' % (sysbl,i)) print 'email send success.' except Exception ,e: logging.error('%s %s email send failed. %s' % (sysbl,i,e)) print e print 'email send failed.' smtp.quit()
def to_mail(to_name, to_email, subject, body, headers={}, decorate_body=True, email_from=None, name_from=None): try: if email_from is None: email_from = config.get('adhocracy.email.from') if name_from is None: name_from = config.get('adhocracy.site.name') if decorate_body: body = (_(u"Hi %s,") % to_name + u"\r\n\r\n%s\r\n\r\n" % body + _(u"Cheers,\r\n\r\n" u" the %s Team\r\n") % config.get('adhocracy.site.name')) msg = MIMEText(body.encode(ENCODING), 'plain', ENCODING) for k, v in headers.items(): msg[k] = v subject = Header(subject.encode(ENCODING), ENCODING) msg['Subject'] = subject msg['From'] = _("%s <%s>") % (name_from, email_from) to = Header(u"%s <%s>" % (to_name, to_email), ENCODING) msg['To'] = to msg['Date'] = email.Utils.formatdate(time()) msg['X-Mailer'] = "Adhocracy SMTP %s" % version.get_version() #log.debug("MAIL\r\n" + msg.as_string()) send(email_from, to_email, msg.as_string()) except Exception: log.exception("Sending mail failed.")
def compose_email(to_mailbox, from_mailbox, subject, content, to_display_name = None, from_display_name = None, reply_to_mailbox = None, reply_to_display_name = None, sender_mailbox = None, sender_display_name = None, id = None, orig_date = None, **kw): # Constructs the email and adds the content msg = MIMEText(content, _charset='utf-8') # Add mandatory headers msg['Message-Id'] = email.utils.make_msgid(str(id)) if id else email.utils.make_msgid() msg['Date'] = _formatdate(orig_date if orig_date else datetime.datetime.now(pytz.utc)) msg['To'] = _formataddr(to_mailbox, to_display_name, header_name="To") msg['From'] = _formataddr(from_mailbox, from_display_name, header_name="From") subject_header = Header(header_name="Subject") subject_header.append(remove_control_chars(subject)) msg['Subject'] = subject_header # Add "Reply-To" if given if reply_to_mailbox: msg['Reply-To'] = _formataddr(reply_to_mailbox, reply_to_display_name, header_name="Reply-To") # Add "Sender" if given if sender_mailbox: msg['Sender'] = _formataddr(sender_mailbox, sender_display_name, header_name="Sender") return msg
def render_to_email(self): from ..lib.frontend_urls import FrontendUrls email_text_part = self.render_to_email_text_part() email_html_part = self.render_to_email_html_part() if not email_text_part and not email_html_part: return '' frontendUrls = FrontendUrls(self.first_matching_subscription.discussion) msg = email.mime.Multipart.MIMEMultipart('alternative') from email.header import Header msg['Precedence'] = 'list' msg['List-ID'] = self.first_matching_subscription.discussion.uri() msg['Date'] = email.Utils.formatdate() msg['Message-ID'] = "<"+self.event_source_object().message_id+">" if self.event_source_object().parent: msg['In-Reply-To'] = "<"+self.event_source_object().parent.message_id+">" #Archived-At: A direct link to the archived form of an individual email message. msg['List-Subscribe'] = frontendUrls.getUserNotificationSubscriptionsConfigurationUrl() msg['List-Unsubscribe'] = frontendUrls.getUserNotificationSubscriptionsConfigurationUrl() msg['Subject'] = Header(self.get_notification_subject(), 'utf-8') from_header = Header(self.event_source_object().creator.name, 'utf-8') from_header.append(" <" + self.get_from_email_address() + ">", 'ascii') msg['From'] = from_header msg['To'] = self.get_to_email_address() if email_text_part: msg.attach(SafeMIMEText(email_text_part.encode('utf-8'), 'plain', 'utf-8')) if email_html_part: msg.attach(SafeMIMEText(email_html_part.encode('utf-8'), 'html', 'utf-8')) return msg.as_string()
def test_decode_header_multipart(self): """ Two part header: iso-8859-1 and utf-8 """ h = Header(b'M\xfcnchen', 'iso-8859-1') h.append(b' M\xc3\xbcnchen', 'utf-8') header_text = decode_header(h) self.assertEqual('München München', header_text)
def makeEncodedEmail(self, encoding_name, actual_encoding): email = self.factory.makeEmailMessage(body=self.high_characters) email.set_type('text/plain') email.set_charset(encoding_name) macroman = Header(self.high_characters, actual_encoding).encode() new_subject = macroman.replace(actual_encoding, encoding_name) email.replace_header('Subject', new_subject) return email
def encode_string(name, value, maxlinelen=None): try: header = Header(value.encode("ascii"), "ascii", maxlinelen, header_name=name) except UnicodeEncodeError: header = Header(value.encode("utf-8"), "utf-8", header_name=name) return header.encode(splitchars=' ;,')
def format_str(s): # encode if contain utf-8 or else cannot be correctly dispalyed name,addr = parseaddr(s) print 'name:',name,'addr:',addr head = Header(name,'utf-8') print 'head:',head,'encode:',head.encode() print 'addr encode:',addr.encode() return formataddr((head.encode(),addr.encode()))
def encode_address(address, encoding): parts = re.split("<|>", address.replace('"', "")) name = parts[0] if len(parts) > 1: name = Header(name.encode(encoding.lower()), encoding.upper()).encode() name += " <" + parts[1] + ">" return name
def create_and_send_mail_messages(messages): if not settings.EMAIL_HOST: return sender = Header(unicode(settings.APP_SHORT_NAME), 'utf-8') sender.append('<%s>' % unicode(settings.DEFAULT_FROM_EMAIL)) sender = u'%s <%s>' % (unicode(settings.APP_SHORT_NAME), unicode(settings.DEFAULT_FROM_EMAIL)) reply_to = unicode(settings.DEFAULT_REPLY_TO_EMAIL) try: connection = None if sender is None: sender = str(settings.DEFAULT_FROM_EMAIL) for recipient, subject, html, text, media in messages: if connection is None: connection = create_connection() msgRoot = MIMEMultipart('related') msgRoot['Subject'] = Header(subject, 'utf-8') msgRoot['From'] = sender to = Header(u"%s <%s>" % (recipient.username, recipient.email), 'utf-8') msgRoot['To'] = to if reply_to: msgRoot['Reply-To'] = reply_to msgRoot.preamble = 'This is a multi-part message from %s.' % unicode(settings.APP_SHORT_NAME).encode('utf8') msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgAlternative.attach(MIMEText(text.encode('utf-8'), _charset='utf-8')) msgAlternative.attach(MIMEText(html.encode('utf-8'), 'html', _charset='utf-8')) for alias, location in media.items(): fp = open(location, 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<'+alias+'>') msgRoot.attach(msgImage) try: connection.sendmail(sender, [recipient.email], msgRoot.as_string()) except SMTPRecipientsRefused, e: logging.error("Email address not accepted. Exception: %s" % e) except Exception, e: logging.error("Couldn't send mail using the sendmail method: %s" % e) try: connection.quit() except Exception, e: logging.error(e)
def test_reply_to(mailer): msg = mailer.mail( subject="testing", recipients=["*****@*****.**"], sender="spammer <*****@*****.**>", reply_to="somebody <*****@*****.**>", body="testing") h = Header( "Reply-To: %s" % sanitize_address('somebody <*****@*****.**>')) assert h.encode() in str(msg)
def get_header(self, name, value=None): """ Return a single email header :param name: the header name :return: Header instance """ _header = Header(header_name=name, charset=self.charset) if value: _header.append(value) return _header
def encode_header(self, value): """ Encode an HTTP header value. Try first natively in ISO-8859-1, then UTF-8 encoded quoted string. """ try: return smart_unicode(value).encode('iso-8859-1') except UnicodeEncodeError: header = Header(smart_unicode(value), 'utf-8') return header.encode()
def test_reply_to(self): msg = Message(subject="testing", recipients=["*****@*****.**"], sender="spammer <*****@*****.**>", reply_to="somebody <*****@*****.**>", body="testing") response = msg.as_string() h = Header("Reply-To: %s" % sanitize_address('somebody <*****@*****.**>')) self.assertIn(h.encode(), str(response))
def get_emails_header(self, attr): c = Charset(self.charset) c.header_encoding = QP c.body_encoding = 0 r = Charset(self.charset) r.header_encoding = 0 r.body_encoding = 0 h = Header() self.normalize_email_list(attr) emails = self.__getattribute__(attr) for i in range(len(emails)): name, email = emails[i] if i: h.append(',', r) if name: name = name.encode(self.charset, 'xmlcharrefreplace') h.append(name, r if is7bit(name) else c) h.append('<%s>' % email, r) else: h.append(email, r) return h
def send_html_email(self, to_, from_=None, subject=None, text=None, html=None, charset="utf-8"): message = MIMEMultipart("alternative") if subject: subject_header = Header() subject = (codecs.decode(bytearray(subject, sys.getdefaultencoding()), charset) if isinstance(subject, str) else subject) subject_header.append(subject.strip()) message["Subject"] = subject_header from_ = from_ or self.default_sender from_ = (codecs.decode(bytearray(from_, sys.getdefaultencoding()), charset) if isinstance(from_, str) else from_) from_realname, from_addr = parseaddr(from_) from_header = Header() from_header.append(formataddr((from_realname, from_addr))) message['From'] = from_header to_ = (codecs.decode(bytearray(to_, sys.getdefaultencoding()), charset) if isinstance(to_, str) else to_) to_realname, to_addr = parseaddr(to_) to_header = Header() to_header.append(formataddr((to_realname, to_addr))) message['To'] = to_header message.attach(MIMEText(text, "plain", charset)) message.attach(MIMEText(html, "html", charset)) self._send(message, from_addr, to_addr)
def send_email(self, to_, from_=None, subject=None, body=None, subtype="plain", charset="utf-8"): message = MIMEText(body, subtype, charset) if subject: subject_header = Header() subject = (codecs.decode(bytearray(subject, sys.getdefaultencoding()), charset) if isinstance(subject, str) else subject) subject_header.append(subject.strip()) message["Subject"] = subject_header from_ = from_ or self.default_sender from_ = (codecs.decode(bytearray(from_, sys.getdefaultencoding()), charset) if isinstance(from_, str) else from_) from_realname, from_addr = parseaddr(from_) from_header = Header() from_header.append(formataddr((from_realname, from_addr))) message['From'] = from_header to_ = (codecs.decode(bytearray(to_, sys.getdefaultencoding()), charset) if isinstance(to_, str) else to_) to_realname, to_addr = parseaddr(to_) to_header = Header() to_header.append(formataddr((to_realname, to_addr))) message['To'] = to_header self._send(message, from_addr, to_addr)
def modify_header(self, *args): '''Generate the content for the :mailheader:`Sender` header. :returns: The *mailbox* of the group (a display-name and an angle-address). :rtype: str''' name = to_unicode_or_bust(self.groupInfo.name) h = Header(name, UTF8) headerName = h.encode() addr = self.listInfo.get_property('mailto') retval = formataddr((headerName, addr)) return retval
def _write_headers(self, msg): for h, v in msg.items(): print("%s:" % h, end=" ", file=self._fp) if isinstance(v, Header): print(v.encode(maxlinelen=self._maxheaderlen), file=self._fp) else: # Header's got lots of smarts, so use it. header = Header(v, maxlinelen=self._maxheaderlen, header_name=h) print(header.encode(), file=self._fp) # A blank line always separates headers from body print(file=self._fp)
def sendEmail(authInfo, fromAdd, toAdd, subject, plainText, htmlText): strFrom = fromAdd #if isinstance(toAdd,list) : # strTo = ', '.join(toAdd) #else : strTo = toAdd server = authInfo.get('server') user = authInfo.get('user') passwd = authInfo.get('password') if not (server and user and passwd) : print 'incomplete login info, exit now' return # 设定root信息 msgRoot = MIMEMultipart('related') msgRoot['Subject'] = subject h = Header('Etekcitizen','utf-8') h.append('<'+strFrom+'>', 'ascii') msgRoot['From'] = h msgRoot['To'] = strTo print strTo , user , server msgRoot.preamble = 'This is a multi-part message in MIME format.' # Encapsulate the plain and HTML versions of the message body in an #'alternative' part, so message agents can decide which they want to display. msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) #设定纯文本信息 #msgText = MIMEText(plainText, 'plain', 'utf-8') #msgAlternative.attach(msgText) #设定HTML信息 msgText = MIMEText(htmlText, 'html', 'utf-8') msgAlternative.attach(msgText) #设定内置图片信息 #fp = open('test.jpg', 'rb') #msgImage = MIMEImage(fp.read()) #fp.close() #msgImage.add_header('Content-ID', '<image1>') #msgRoot.attach(msgImage) try : #发送邮件 smtp = smtplib.SMTP() #设定调试级别,依情况而定 smtp.set_debuglevel(0) smtp.connect(server) smtp.login(user, passwd) smtp.sendmail(strFrom, strTo, msgRoot.as_string()) smtp.quit() return True; except Exception, e: file = open('error.txt','a') file.write(time.strftime('%Y-%m-%d %H:%M:%S') + str(e)) file.write('\n-------------\n') file.close() return False;
def _write_headers(self, msg): for h, v in msg.items(): self.write('%s: ' % h) if isinstance(v, Header): self.write(v.encode( maxlinelen=self._maxheaderlen, linesep=self._NL)+self._NL) else: # Header's got lots of smarts, so use it. header = Header(v, maxlinelen=self._maxheaderlen, header_name=h) self.write(header.encode(linesep=self._NL)+self._NL) # A blank line always separates headers from body self.write(self._NL)
def sendMail_HTML(server, user, password, From, To, subject, body, file_list, reply_to, encode, bLogin=False): server = smtplib.SMTP(server) server.docmd("EHLO server") if bLogin: server.starttls() server.login(user, password) main_msg = email.MIMEMultipart.MIMEMultipart() # text_msg = email.MIMEText.MIMEText(body) text_msg = email.MIMEText.MIMEText(body, "html", encode) main_msg.attach(text_msg) contype = "application/octet-stream" maintype, subtype = contype.split("/", 1) for file_name in file_list: try: data = open(file_name, "rb") file_msg = email.MIMEBase.MIMEBase(maintype, subtype) file_msg.set_payload(data.read()) data.close() email.Encoders.encode_base64(file_msg) basename = os.path.basename(file_name) file_msg.add_header("Content-Disposition", "attachment", filename=basename) main_msg.attach(file_msg) except: pass frmHeader = Header("server status report", encode) frmHeader.append("<" + From + ">", "ascii") main_msg["From"] = frmHeader main_msg["To"] = To main_msg["Reply-To"] = reply_to main_msg["Subject"] = Header(subject, encode) main_msg["Date"] = email.Utils.formatdate() fullText = main_msg.as_string() # 用smtp发送邮件 try: result = server.sendmail(From, To, fullText) return result finally: server.quit() return None
# 定义发送人邮箱信息 SMTP_SERVER = 'smtp.yandex.ru' EMAIL_USER = '******' EMAIL_PASS = '******' # 定义发件人、收件人邮箱 sender = EMAIL_USER receiver = '*****@*****.**' # 定义邮件内容 message = MIMEText( "Navigate your code with ease. Click on function and method calls to jump to their definitions or references in the same repository. Learn more", "plain", "utf-8") # 定义收件人、发件人和邮件主题、如果不定义~可能会引发554垃圾邮件的检查错误 message['subject'] = Header('《脑筋急转弯》', 'utf-8') message['from'] = sender message['to'] = receiver # 连接邮件服务器 server = smtplib.SMTP_SSL(SMTP_SERVER, 465) # 设置信息展示级别 server.set_debuglevel(1) # 登录邮箱服务器 server.login(EMAIL_USER, EMAIL_PASS) # 发送邮件 server.sendmail(sender, [receiver], message.as_string()) # 退出并关闭客户端 server.quit()
import smtplib from email.mime.text import MIMEText from email.header import Header mailhost = 'smtp.qq.com' qqmail = smtplib.SMTP_SSL(mailhost, 465) account = input('请输入你的邮箱:') password = input('请输入你的密码:') #不是账号密码,是登录第三方客户端邮箱的授权码 qqmail.login(account, password) receiver = input('请输入收件人的邮箱:') content = input('请输入邮件正文:') message = MIMEText(content, 'plain', 'utf-8') #实例化一个MIMEText邮件对象,该对象需要写进三个参数,分别是邮件正文,文本格式和编码 subject = input('请输入你的邮件主题:') message['From'] = Header(account) message['To'] = Header(receiver) message['Subject'] = Header(subject, 'utf-8') try: qqmail.sendmail(account, receiver, message.as_string()) print('邮件发送成功') except: print('邮件发送失败') qqmail.quit()
smtp_server = 'smtp.qq.com' text = '''亲爱的学员,你好! 我是吴枫老师,能遇见你很开心。 希望学习Python对你不是一件困难的事情! 人生苦短,我用Python ''' # 邮箱正文内容,第一个参数为内容,第二个参数为格式(plain 为纯文本),第三个参数为编码 msg = MIMEText(text,'plain','utf-8') # 邮件头信息 msg['From'] = Header(from_addr) msg['To'] = Header(",".join(to_addrs)) msg['Subject'] = Header('猫狗合作') # 开启发信服务,这里使用的是加密传输 server = smtplib.SMTP_SSL(smtp_server) server.connect(smtp_server,465) # 登录发信邮箱 server.login(from_addr, password) # 发送邮件 server.sendmail(from_addr, to_addrs, msg.as_string()) # 关闭服务器 server.quit()
from email.mime.multipart import MIMEMultipart import smtplib account = Configruation.USERNAME + '@ericsson.com' sender = Configruation.EMAILSENDER #'*****@*****.**' receivers = Configruation.EMAILRECVIERS passwd = str(Configruation.USERPASSWORD,'utf-8') mailcontents = Configruation.EMAILSUJECT mailserver = 'se-smtp.ericsson.se' sub = 'Product Delivery Update Notify' xmlFileName = './DeliveryInformation.xml' try: msg = MIMEMultipart('related') print('mail sender is :' + str(sender)) msg['From'] = formataddr(["sender", sender]) print('mail recvier list:'+ ','.join(receivers)) msg['To'] = Header(",".join(receivers)) #formataddr(["receiver", receive]) msg['Subject'] = mailcontents print('mail Subject is :' + str(mailcontents)) #contents information # msg.attach(txt) # txt = MIMEText(Configruation.LOGINURL+'?title='+Configruation.LOGINJUMPTOPAGE, 'plain', 'utf-8') # msg.attach(txt) #attach file # attach = MIMEApplication(open("D:\xx\\tool\pycharm\\1.csv").read()) # attach.add_header('Content-Disposition', 'attachment', filename='1.csv') # msg.attach(attach) tableHeadTemplate = ' <td style= "color:white" align="center">{0}</td>' tableContentsTemplate = '<td align="center">{0}</td>' tableContentsLinkTemplate = '<a href = {0}> {1} </a>' emailCommentsTemplate = '<h4 id ="155" font > <strong> {0} </strong> </h4> <p style="text-indent:1em">{1}</p>' # emailCommentsContentsTemplate = '<p style="text-indent:1em;" class="comments" >{0}</p>'
def send_email(request): try: # --------------------------准备数据-------------start------------- # 发送邮箱 from_addr = "*****@*****.**" # 程序代码中登录的密码其实就是那个你设置的授权码 password = "******" # 发送服务器 smtp_server = "smtp.163.com" # 接收邮箱 to_addr = request.POST.get('email') # 用户名 username = request.POST.get('username') # 密码 u_pwd = request.POST.get('password') # 使用md5加密 u_pwd = md5(u_pwd.encode(encoding='utf-8')).hexdigest() # 激活码 code = ''.join(str(uuid.uuid4()).split('-')) # 10分钟后的时间戳 td = timedelta(minutes=10) ts = datetime.now() + td ts = str(ts.timestamp()).split('.')[0] # --------------------------准备数据---------------end----------- # -----------------------插入数据库数据----------start-------------- user = User(username=username, password=u_pwd, email=to_addr, code=code, timestamp=ts) user.save() # -----------------------插入数据库数据----------end-------------- # ------------------------构建邮件内容对象----------start-------------- html = """ <html> <body> <div> Email 地址验证<br> 这封信是由 上海尚学堂 发送的。<br> 您收到这封邮件,是由于在 上海尚学堂CRM系统 进行了新用户注册,或用户修改 Email 使用了这个邮箱地址。<br> 如果您并没有访问过 上海尚学堂CRM,或没有进行上述操作,请忽略这封邮件。您不需要退订或进行其他进一步的操作。<br> ----------------------------------------------------------------------<br> 帐号激活说明<br> ----------------------------------------------------------------------<br> 如果您是 上海尚学堂CRM 的新用户,或在修改您的注册 Email 时使用了本地址,我们需要对您的地址有效性进行验证以避免垃圾邮件或地址被滥用。<br> 您只需点击下面的链接激活帐号即可:<br> <a href="http://www.crm.com/active_accounts/?username={}&code={}×tamp={}">http://www.crm.com/active_accounts/?username={}&code={}&timestamp={}</a><br/> 感谢您的访问,祝您生活愉快!<br> 此致<br> 上海尚学堂 管理团队. </div> </body> </html> """.format(username, code, ts, username, code, ts) msg = MIMEText(html, "html", "utf-8") # 标准邮件需要三个头部信息: From To 和 Subject # 设置发件人和收件人的信息 u/U:表示unicode字符串 # 比如:尚学堂 <*****@*****.**> msg['From'] = format_addr(u'尚学堂<%s>' % from_addr) # 发件人 to_name = username # 收件人名称 msg['To'] = format_addr(u'{}<%s>'.format(to_name) % to_addr) # 收件人 # 设置标题 # 如果接收端的邮件列表需要显示发送者姓名和发送地址就需要设置Header,同时中文需要encode转码 msg['Subject'] = Header(u'CRM系统官网帐号激活邮件', 'utf-8').encode() # ------------------------构建邮件内容对象-----------end------------- # ------------------------------发送--------------start---------------- # 创建发送邮件服务器的对象 server = smtplib.SMTP(smtp_server, 25) # 设置debug级别0就不打印发送日志,1打印 server.set_debuglevel(1) # 登录发件邮箱 server.login(from_addr, password) # 调用发送方法 第一个参数是发送者邮箱,第二个是接收邮箱,第三个是发送内容 server.sendmail(from_addr, [to_addr], msg.as_string()) # 关闭发送 server.quit() # ------------------------------发送----------------end-------------- # 返回页面提示信息 return JsonResponse({'code': 200, 'msg': '注册成功,请前往邮箱激活帐号'}) except smtplib.SMTPException as e: # 返回页面提示信息 return JsonResponse({'code': 400, 'msg': '注册失败,请重新注册'})
#!/usr/bin/python # -*- coding: UTF-8 -*- import smtplib from email.mime.text import MIMEText from email.header import Header import pdb smtp_server='smtp.xxx.com' mail_user'*****@*****.**' mail_pass='******' # note to differ SMTP password from log-in password sender = '*****@*****.**' receivers = ['*****@*****.**>'] message = MIMEText(u'This is context.', 'plain', 'utf-8') message['From'] = Header(u'AAA<*****@*****.**>','utf-8') message['To'] = Header(u'BBB<*****@*****.**>') subject = u'Python SMTP Test' message['Subject'] = Header(subject, 'utf-8') try: server = smtplib.SMTP(smtp_server, 25) # server.set_debuglevel(1) # uncomment this to check which error you meet server.login(mail_user,mail_pass) server.sendmail(sender, receivers, message.as_string()) print u'E-mail is sent successfully!' except smtplib.SMTPException: print u'Error: can\'t send an e-mail.'
def send_email(newfile): # 打开文件 f = open(newfile, 'rb') # 读取文件内容 mail_body = f.read() # 调试使用 # print u'打印' # print mail_body # 关闭文件 f.close() # 发送邮箱服务器 smtpserver = 'smtp.qq.com' # 发送邮箱用户名/密码 user = '******' password = '******' # 发送邮箱 sender = '*****@*****.**' # 多个接收邮箱,单个收件人的话,直接是receiver='*****@*****.**' receiver = ['*****@*****.**'] # 发送邮件主题 subject = '自动化测试报告 ' + str( time.strftime("%Y%m%d %H:%M:%S", time.localtime())) # 编写 HTML类型的邮件正文 # MIMEText这个效果和下方用MIMEMultipart效果是一致的,已通过。 # msg = MIMEText(mail_body,'html','utf-8') msg = MIMEMultipart('mixed') # 注意:由于msg_html在msg_plain后面,所以msg_html以附件的形式出现 # text = "Dear all!\nThe attachment is new testreport.\nPlease check it." # 中文测试ok # text = "Dear all!\n附件是最新的测试报告。\n麻烦下载下来看,用火狐浏览器打开查看。\n请知悉,谢谢。" # msg_plain = MIMEText(text,'plain', 'utf-8') # msg.attach(msg_plain) msg_html1 = MIMEText(mail_body, 'html', 'utf-8') msg.attach(msg_html1) msg_html = MIMEText(mail_body, 'html', 'utf-8') msg_html["Content-Disposition"] = 'attachment; filename="TestReport.html"' msg.attach(msg_html) # 以附件的方式发送:但是会报554,倍163退信。--此路不通。 # msg_html = MIMEText(mail_body,'base64','utf-8') # msg_html["Content-Type"] = 'application/octet-stream' # msg_html.add_header('Content-Disposition', 'attachment', filename='testreport.html') # msg.attach(msg_html) # 要加上msg['From']这句话,否则会报554的错误。 # 要在163有限设置授权码(即客户端的密码),否则会报535 msg['From'] = '[email protected] <*****@*****.**>' # msg['To'] = '*****@*****.**' # 多个收件人 msg['To'] = ";".join(receiver) msg['Subject'] = Header(subject, 'utf-8') # 连接发送邮件 smtp = smtplib.SMTP() smtp.connect(smtpserver, 25) smtp.login(user, password) smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit()
Header(name, 'utf-8').encode(), \ addr.encode('utf-8') if isinstance(addr, unicode) else addr)) from_addr = '' #发件人邮箱 password = '' #发件人邮箱密码 to_addr = '' #收件人邮箱 #发件人邮箱可与收件人邮箱相同,即自己发给自己 smtp_server = 'smtp.qq.com' #邮箱服务器 #随机从sentence.txt中获取一个励志句子 with open('sentence.txt', 'r') as f: text = f.read() pattern = re.compile(r'.*?\n', re.S) match = pattern.findall(text) num = random.randint(0, len(match) - 1) sentence = match[num] #发送信息 msg = MIMEText(sentence, 'plain', 'utf-8') msg['From'] = _format_addr(u'CentOS服务器 <%s>' % from_addr) msg['To'] = _format_addr(u'xzjqx <%s>' % to_addr) msg['Subject'] = Header(u'每日一句正能量^_^', 'utf-8').encode() server = smtplib.SMTP(smtp_server, 25) server.ehlo() server.starttls() server.login(from_addr, password) server.sendmail(from_addr, [to_addr], msg.as_string()) server.quit()
def formatAddr(s): name, addr = parseaddr(s) return formataddr((Header(name, 'utf-8').encode(), addr))
def send_all_mail(self): self.send_mail_button.config(state='disabled') self.pause_button.config(state='enabled') self.app_state.config(text='Running...') self.app_worked = True self.is_paused = False self.i = 0 while len(self.smtp_list) > 0 and self.is_paused is False: if self.i == int(self.quota_entry.get()): self.i = 0 self.smtp_list.pop(0) if len(self.smtp_list) > 0 and len(self.emails) > 0: EMAIL_ADDRESS = self.smtp_list[0][0] EMAIL_PASSWORD = self.smtp_list[0][1] EMAIL_HOST = self.smtp_list[0][2] EMAIL_PORT = self.smtp_list[0][3] else: break if str(EMAIL_PORT) == '25' or str(EMAIL_PORT) == '587': # print(f"Port Using 25 or 587 {EMAIL_PORT}") self.server = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT) self.server.ehlo() self.server.starttls() self.server.ehlo() else: # print("Wrong port") with open('Logs\\error_log.txt', 'a') as f: f.write( f"PORT_ERROR -> Login Failed to {EMAIL_ADDRESS} Use port -> '25' or '587'\n" ) self.smtp_list.pop(0) continue try: self.server.login(EMAIL_ADDRESS, EMAIL_PASSWORD) # print(f"Logged In to {EMAIL_ADDRESS}") with open('Logs\\success_log.txt', 'a') as f: f.write(f"SUCCESS -> Logged in to {EMAIL_ADDRESS}\n") except smtplib.SMTPAuthenticationError: # print("Login Failed") with open('Logs\\error_log.txt', 'a') as f: f.write( f"SMTPAuthenticationError -> Login Failed to {EMAIL_ADDRESS} \n" ) self.smtp_list.pop(0) self.server.quit() continue while self.i < int(self.quota.get()) and self.is_paused is False: if len(self.emails) > 0: msg = EmailMessage() msg['From'] = formataddr( (str(Header(self.from_text.get(), 'utf-8')), EMAIL_ADDRESS)) msg['To'] = self.emails[0] msg['Subject'] = self.subject_text.get() msg.add_alternative(self.html_text.get('1.0', END), subtype='html') else: break try: self.server.send_message(msg, EMAIL_ADDRESS) self.email_sent += 1 self.mail_sent.config(text="Mail sent : " + str(self.email_sent)) self.mail_sending_to.config( text=f"Sent to : \n{self.emails[0]}") with open('Logs\\success_log.txt', 'a') as f: f.write( f"\t SUCCESS -> Mail sent to {self.emails[0]}\n") # print(f"Mail sent to {self.emails[0]}") self.emails.pop(0) self.i += 1 if self.i >= int(self.quota.get()): self.server.quit() except: # print('Email send failed') break if self.is_paused is True: self.send_mail_button.config(text="Resume") self.app_state.config(text='Paused...') else: self.app_state.config(text='Finised') self.create_report() self.send_mail_button.config(state='enabled') self.quota_entry.config(state='readonly')
def _format_address(s): name, address = parseaddr(s) return formataddr((Header(name, 'utf-8').encode(), address))
import smtplib def _format_addr(s): name, addr = parseaddr(s) return formataddr( (Header(name, 'utf-8').encode(), addr.encode('utf-8') if isinstance(addr, unicode) else addr)) cp = ConfigParser.SafeConfigParser() cp.read('myapp.conf') from_add = cp.get('email', '163user') from_pwd = cp.get('email', '163pwd') to_add = cp.get('email', 'qquser') hostname = cp.get('email', '163SMTP') # 必要信息必须填99%,否则会报错554 msg = MIMEText('hello, send by Python...', 'plain', 'utf-8') msg['Subject'] = Header(u'来自SMTP的问候……', 'utf-8').encode() msg['From'] = _format_addr(u'Python爱好者 <%s>' % from_add) msg['To'] = _format_addr(u'管理员 <%s>' % to_add) server = smtplib.SMTP_SSL(hostname) server.set_debuglevel(1) server.login(from_add, from_pwd) # 密码必须是特别授权的密码,不是原来的密码 server.sendmail(from_add, [to_add], msg.as_string()) server.quit() print 'success'
import smtplib from email.mime.text import MIMEText from email.header import Header if __name__ == '__main__': sender = '*****@*****.**' # Receiver's email receivers = ['*****@*****.**'] # Three Params: # 1.Content of message # 2.Content format # 3.Set utf-8 code message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8') # Sender message['From'] = Header("菜鸟教程", 'utf-8') # Receiver message['To'] = Header("测试", 'utf-8') subject = 'Python SMTP 邮件测试' message['Subject'] = Header(subject, 'utf-8') try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, receivers, message.as_string()) print("邮件发送成功") except smtplib.SMTPException: print("Error: 无法发送邮件")
def _format_addr(self, s): name, addr = parseaddr(s) return formataddr( (Header(name, 'utf-8').encode(), addr.encode('utf-8') if isinstance(addr, unicode) else addr))
from email.mime.application import MIMEApplication from email.header import Header for i in range(data.shape[0]): data1 = data[i].values.tolist() smtpserver = smtpserver1 username = username1 password = password1 sender = sender1 for n in data1: try: if type(n) != str: continue receiver = n subject = subject1 subject = Header(subject, 'utf-8').encode() msg = MIMEMultipart('mixed') msg['Subject'] = subject msg['From'] = a msg['To'] = n text = text1 text_plain = MIMEText(text, 'plain', 'utf-8') msg.attach(text_plain) for file_name in fff: # 构造附件 xlsxpart = MIMEApplication(open(file_name, 'rb').read()) # filename表示邮件中显示的附件名 b = file_name.split("\\", -1)[-1] xlsxpart.add_header('Content-Disposition', 'attachment', filename=b)
def send_mail(self, subject, content, *file_paths, **kwargs): """ 发送邮件主函数 :param subject: 邮件主题 :param content: 邮件正文 :param file_paths: 邮件附件(列表) :param kwargs: dict 邮件服务器设置 :keyword host: string smtp服务器地址 :keyword port: int smtp服务器端口号 :keyword username: string 用户名 :keyword password: string 密码 :keyword use_ssl: bool 是否启用ssl,默认True :keyword timeout: int 超时时间,默认10s :keyword sender: string 发件人邮箱 :keyword recipients: string/list 收件人邮箱(列表) :raise: NetworkError/MailerException :return: """ # 重新赋值邮件配置 host = kwargs.get("host") or self.host port = kwargs.get("port") or self.port username = kwargs.get("username") or self.username password = kwargs.get("password") or self.password use_ssl = kwargs.get("use_ssl") or self.use_ssl timeout = kwargs.get("timeout") or self.timeout sender = kwargs.get("sender") or self.sender recipients = kwargs.get("recipients") or self.recipients # 邮件类型 content_type = 'html' if content.startswith('<html>') else 'plain' # 构造MIMEMultipart对象做为根容器 # 格式化邮件数据 msg = MIMEMultipart() msg.set_charset("utf-8") msg['Subject'] = Header(subject, "utf-8") # 设置主题 msg['From'] = self._format_address(sender) msg['To'] = ', '.join(self._format_list(recipients)) msg['Date'] = formatdate() # msg["Accept-Language"] = "zh-CN" # msg["Accept-Charset"] = "ISO-8859-1,utf-8" # 构造MIMEText对象做为邮件显示内容并附加到根容器---邮件正文--- msg.attach(MIMEText(content, content_type, "utf-8")) # 构造MIMEBase对象做为文件附件内容并附加到根容器---邮件附件--- cid = 0 # 附件序号 for file_path in file_paths: if not os.path.isfile(file_path): continue file_name = os.path.basename(file_path) main_type, sub_type = self._get_file_type(file_name) mime = MIMEBase(main_type, sub_type, filename=file_name) mime.add_header('Content-Disposition', 'attachment', filename=file_name) # 设置附件头 mime.add_header('Content-ID', '<%s>' % cid) mime.add_header('X-Attachment-Id', '%s' % cid) # 读入文件内容并格式化 with open(file_path, 'rb') as f: mime.set_payload(f.read()) encode_base64(mime) msg.attach(mime) cid += 1 pass self.logger.debug('Send mail form %s to %s' % (msg['From'], msg['To'])) # 初始并连接smtp服务器 conn_func = smtplib.SMTP_SSL if use_ssl else smtplib.SMTP server = conn_func(host, port, timeout=timeout) try: # 开启调试模式 # server.set_debuglevel(1) # 如果存在用户名密码则尝试登录 if username and password: server.login(username, password) # 登陆服务器 # 发送邮件 server.sendmail(sender, recipients, msg.as_string().encode("utf8")) self.logger.debug('Mail sent success.') except socket.gaierror as e: # 网络无法连接 self.logger.exception(e) raise NetworkError(e) except smtplib.SMTPServerDisconnected as e: # 网络连接异常 self.logger.exception(e) raise NetworkError(e) except smtplib.SMTPException as e: # 邮件发送异常 self.logger.exception(e) raise MailerException(e) except Exception as e: self.logger.error('{}=>{}'.format(type(e), e)) raise MailerException(e) finally: # 关闭stmp连接 server.quit() server.close() pass pass
addr_list = s.split(',') new_addr_list = [] for item in addr_list: name, addr = parseaddr(item) new_addr_list.append(formataddr((Header(name, 'utf-8').encode(), addr))) return ','.join(new_addr_list) # from_addr = 'm1******[email protected]' # password = "******" # MAIL_USERNAME = '******' # 发件人邮箱 # MAIL_PASSWORD = '******' from_addr = '*****@*****.**' password = "******" to_addr = '8******[email protected],[email protected]' to_addr_list = ['8******[email protected]', '*****@*****.**'] msg = MIMEText('hello sqy', 'plain', 'utf-8') msg['Form'] = _format_addr(from_addr) msg['To'] = _format_addr(to_addr) msg['Subject'] = Header('FLASK API ERROR', 'utf-8').encode() # SMTP_SERVER = 'smtp.exmail.qq.com' smtp_server = "smtp.exmail.qq.com" smtp_port = 25 server = smtplib.SMTP(smtp_server, smtp_port) server.set_debuglevel(1) server.login(from_addr, password) server.sendmail(from_addr, to_addr_list, msg.as_string()) server.quit()
from email.header import Header from email.mime.text import MIMEText from email.utils import parseaddr, formataddr import smtplib def _format_addr(s): name, addr = parseaddr(s) return formataddr((Header(name, 'utf-8').encode(), addr)) from_addr = '*****@*****.**' password = '******' # password = '******' to_addr = '*****@*****.**' smtp_server = 'smtp.163.com' msg = MIMEText('很高心见到你,这是来自网络实验的测试邮件', 'plain', 'utf-8') msg['From'] = _format_addr('zqydwqe<%s>' % from_addr) msg['To'] = _format_addr('抱歉打扰 <%s>' % to_addr) msg['Subject'] = Header('测试邮件', 'utf-8').encode() server = smtplib.SMTP(smtp_server, 25) server.set_debuglevel(1) server.login(from_addr, password) server.sendmail(from_addr, [to_addr], msg.as_string()) server.quit()
def _format_addr(s): name, addr = parseaddr(s) return formataddr( (Header(name, 'utf-8').encode(), addr)) #如果包含中文,需要通过Header对象进行编码。
def create_message(self, msg): message = MIMEText(msg, 'plain', 'gb2312') message['From'] = Header('hello <%s>' % (self.from_addr), 'gb2312') message['To'] = Header('world <%s>' % (self.to_addr), 'gb2312') message['Subject'] = Header('%s' % ('开始搞事情'), 'gb2312') return message
def format_addr(s): name, addr = parseaddr(s) # 比如:尚学堂 <*****@*****.**> # 因为name可能会有中文,需要对中文进行编码 return formataddr((Header(name, 'utf-8').encode('utf-8'), addr))
def sendemail(db_id, dry_run, filename='', title='slow_query'): MAIL_CONFIG = get_setttings('mail_config') mail_receiver = MAIL_CONFIG['mail_receiver'].split(";") mailenv = MAIL_CONFIG['env'] if mail_receiver == "": logger.info("do not send email") return mail_host = MAIL_CONFIG['mail_host'] mail_user = MAIL_CONFIG['mail_user'] mail_pass = MAIL_CONFIG['mail_pass'] message = MIMEMultipart() message['From'] = Header('DBA', 'utf-8') message['To'] = Header('devops', 'utf-8') if title == 'act_session': kill_opt = get_setttings("id_" + db_id) subject = '(%s) %s active session has been take snapshot' % (mailenv, db_id) message.attach( MIMEText( 'db有超过阀值的活动会话,阀值为:<strong>' + kill_opt['db_act_sess'] + '</strong> <br/>', 'html', 'utf-8')) elif title == 'active_trx': kill_opt = get_setttings("id_" + db_id) subject = '(%s) %s active transaction has been take snapshot' % ( mailenv, db_id) message.attach( MIMEText( 'db有超过阀值的活动事务,阀值为:<strong>' + kill_opt['active_trx_max_cnt'] + '</strong> <br/>', 'html', 'utf-8')) elif title == 'trx_rseg_history_len': kill_opt = get_setttings("id_" + db_id) subject = '(%s) %s trx_rseg_history_len has been take snapshot' % ( mailenv, db_id) message.attach( MIMEText( 'db trx_rseg_history_len 超过阀值,阀值为:<strong>' + kill_opt['trx_rseg_history_len'] + '</strong> <br/>', 'html', 'utf-8')) else: subject = '(%s) %s slow query has been take snapshot' % (mailenv, db_id) message.attach( MIMEText('db有慢查询, threads <strong>' + dry_run + '</strong> <br/>', 'html', 'utf-8')) message['Subject'] = Header(subject, 'utf-8') message.attach( MIMEText( '<br/>You can find more info(snapshot) in the attachment : <strong> ' + filename + ' </strong> processlist:<br/><br/>', 'html', 'utf-8')) with open(work_dir + 'processlist_' + db_id + '.txt', 'r') as f: # with open(filename, 'rb')as f: filecontent = f.readlines() att1 = MIMEText("<br/>".join(filecontent), 'html', 'utf-8') att2 = MIMEText(open(filename, 'rb').read(), 'base64', 'utf-8') att2["Content-Type"] = 'application/octet-stream' att2["Content-Disposition"] = 'attachment; filename=%s' % filename message.attach(att1) message.attach(att2) try: print("entry mail process:%s" % title) smtpObj = smtplib.SMTP_SSL(host=mail_host, port=465, timeout=30) smtpObj.ehlo() print("email begin login...:%s" % title) smtpObj.login(mail_user, mail_pass) print("email login OK! begin send mail...:%s" % title) smtpObj.sendmail(mail_user, mail_receiver, message.as_string()) logger.info("Email sending succeed:%s" % title) except smtplib.SMTPException as err: logger.critical("Error email content:%s ::%s" % (err, title)) logger.critical("Error: 发送邮件失败(%s, %s)", err.args[0], err.args[1].__str__()) except Exception as a: logger.error("send mail fail %s", a) finally: smtpObj.quit()
def _mail_recipient(recipient_name, recipient_email, sender_name, sender_url, subject, body, headers=None): if not headers: headers = {} mail_from = config.get('smtp.mail_from') reply_to = config.get('smtp.reply_to') msg = MIMEText(body.encode('utf-8'), 'plain', 'utf-8') for k, v in headers.items(): if k in msg.keys(): msg.replace_header(k, v) else: msg.add_header(k, v) subject = Header(subject.encode('utf-8'), 'utf-8') msg['Subject'] = subject msg['From'] = _("%s <%s>") % (sender_name, mail_from) recipient = u"%s <%s>" % (recipient_name, recipient_email) msg['To'] = Header(recipient, 'utf-8') msg['Date'] = utils.formatdate(time()) msg['X-Mailer'] = "CKAN %s" % ckan.__version__ if reply_to and reply_to != '': msg['Reply-to'] = reply_to # Send the email using Python's smtplib. smtp_connection = smtplib.SMTP() if 'smtp.test_server' in config: # If 'smtp.test_server' is configured we assume we're running tests, # and don't use the smtp.server, starttls, user, password etc. options. smtp_server = config['smtp.test_server'] smtp_starttls = False smtp_user = None smtp_password = None else: smtp_server = config.get('smtp.server', 'localhost') smtp_starttls = ckan.common.asbool(config.get('smtp.starttls')) smtp_user = config.get('smtp.user') smtp_password = config.get('smtp.password') try: smtp_connection.connect(smtp_server) except socket.error as e: log.exception(e) raise MailerException( 'SMTP server could not be connected to: "%s" %s' % (smtp_server, e)) try: # Identify ourselves and prompt the server for supported features. smtp_connection.ehlo() # If 'smtp.starttls' is on in CKAN config, try to put the SMTP # connection into TLS mode. if smtp_starttls: if smtp_connection.has_extn('STARTTLS'): smtp_connection.starttls() # Re-identify ourselves over TLS connection. smtp_connection.ehlo() else: raise MailerException("SMTP server does not support STARTTLS") # If 'smtp.user' is in CKAN config, try to login to SMTP server. if smtp_user: assert smtp_password, ("If smtp.user is configured then " "smtp.password must be configured as well.") smtp_connection.login(smtp_user, smtp_password) smtp_connection.sendmail(mail_from, [recipient_email], msg.as_string()) log.info("Sent email to {0}".format(recipient_email)) except smtplib.SMTPException as e: msg = '%r' % e log.exception(msg) raise MailerException(msg) finally: smtp_connection.quit()
time.sleep(10) log.warning('Connection unexpectedly closed retry') while True: mission_data = dict() try: mission_data = get_email_mission() message = MIMEText(mission_data['message'], _subtype='html', _charset='utf-8') message['Accept-Language'] = "zh-CN" message['Accept-Charset'] = "ISO-8859-1,UTF-8" message['From'] = encode_header(mission_data['from'], username) message['To'] = encode_header(mission_data['to'], '') message['Message-ID'] = uuid.uuid4().__str__() message['Subject'] = Header(mission_data['subject'], 'utf-8') message['MIME-Version'] = '1.0' server.sendmail(username, [ '*****@*****.**', ], message.as_string()) log.warning('SEND SUCCESS EMAIL {}'.format( mission_data['receivers'])) log.warning('WAITING {} SEC'.format(mission_data['delay'])) time.sleep(int(mission_data['delay'])) except RequestException: log.warning('REQUEST FAILED RETRY') time.sleep(10) except SMTPServerDisconnected: time.sleep(10) log.warning('send email unexpectedly closed retry')
#real coding import smtplib from email.mime.text import MIMEText from email.header import Header # your info user = '******' password = '' # reciver's email to_addr = '@gmail.com' smtp_server = 'smtp.gmail.com' #info to sent text = 'testing' msg = MIMEText(text, 'plain', 'utf-8') msg['From'] = Header(user) msg['To'] = Header(to_addr) msg['Subject'] = Header('Header') # sequire sent // start server server = smtplib.SMTP_SSL(smtp_server) server.connect(smtp_server, 465) # login server.login(user, password) # sent server.sendmail(user, to_addr, msg.as_string()) # close server.quit() #Status #Failed Due to Google rule
from email.mime.text import MIMEText from email.header import Header import smtplib from getpass import getpass mail_host = 'smtp.163.com' mail_user = '******' mail_pwd = getpass() message = MIMEText('hello 最近好不?\n', 'plain', 'utf8') message['From'] = Header('*****@*****.**', 'utf8') message['To'] = Header('*****@*****.**', 'utf8') message['Subject'] = Header('最近好不?', 'utf8') sender = '*****@*****.**' receivers = ['*****@*****.**'] smtp_obj = smtplib.SMTP() smtp_obj.connect(mail_host) smtp_obj.login(mail_user, mail_pwd) smtp_obj.sendmail(sender, receivers, message.as_string())
#!/usr/bin/python # -*- coding: UTF-8 -*- import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header sender = '*****@*****.**' receivers = ['*****@*****.**'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱 mail_host="smtp.qq.com" #设置服务器 mail_user="******" #用户名 mail_pass="******" #口令 #创建一个带附件的实例 message = MIMEMultipart() message['From'] = Header("微信web-Pi", 'utf-8') message['To'] = Header("登录", 'utf-8') subject = '登录确认' message['Subject'] = Header(subject, 'utf-8') #邮件正文内容 message.attach(MIMEText('这是菜鸟教程Python 邮件发送测试……', 'plain', 'utf-8')) # 构造附件1,传送当前目录下的 test.txt 文件 att1 = MIMEText(open('QR.png', 'rb').read(), 'base64', 'utf-8') att1["Content-Type"] = 'application/octet-stream' # 这里的filename可以任意写,写什么名字,邮件中显示什么名字 att1["Content-Disposition"] = 'attachment; filename="QR.png"' message.attach(att1) # # 构造附件2,传送当前目录下的 runoob.txt 文件 # att2 = MIMEText(open('runoob.txt', 'rb').read(), 'base64', 'utf-8') # att2["Content-Type"] = 'application/octet-stream' # att2["Content-Disposition"] = 'attachment; filename="runoob.txt"' # message.attach(att2)
def mail(to, subject, prioflag1, prioflag2, text, reply_to_address=from_address): msg = MIMEMultipart() msg['From'] = str( Header(from_displayname, 'UTF-8').encode() + ' <' + from_address + '> ') msg['To'] = to msg['Reply-To'] = str( Header(from_displayname, 'UTF-8').encode() + ' <' + reply_to_address + '> ') msg['X-Priority'] = prioflag1 msg['X-MSMail-Priority'] = prioflag2 msg['Subject'] = Header(subject, 'UTF-8').encode() body_type = MIMEText(text, "%s" % (message_flag), 'UTF-8') msg.attach(body_type) # now attach the file if file_format != "": fileMsg = email.mime.base.MIMEBase('application', '') fileMsg.set_payload(file(file_format).read()) email.encoders.encode_base64(fileMsg) fileMsg.add_header( 'Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file_format) ) msg.attach(fileMsg) for inline_file in inline_files: if inline_file != "": fileMsg = email.mime.base.MIMEBase('application', '') fileMsg.set_payload(file(inline_file).read()) email.encoders.encode_base64(fileMsg) fileMsg.add_header( 'Content-Disposition', 'inline; filename="%s"' % os.path.basename(inline_file) ) fileMsg.add_header( "Content-ID", "<%s>" % os.path.basename(inline_file) ) msg.attach(fileMsg) mailServer = smtplib.SMTP(smtp, port) io = StringIO() msggen = Generator(io, False) msggen.flatten(msg) if sendmail == 0: if email_provider == "gmail" or email_provider == "yahoo" or email_provider == "hotmail": try: mailServer.starttls() except: pass mailServer.ehlo() else: mailServer.ehlo() try: if provideruser != "" or pwd != "": mailServer.login(provideruser, pwd) mailServer.sendmail(from_address, to, io.getvalue()) else: mailServer.sendmail(from_address, to, io.getvalue()) except: # try logging in with base64 encoding here import base64 try: mailServer.docmd("AUTH LOGIN", base64.b64encode(provideruser)) mailServer.docmd(base64.b64encode(pwd), "") # except exceptions and print incorrect password except Exception as e: print_warning( "It appears your password was incorrect.\nPrinting response: " + (str(e))) return_continue() if sendmail == 1: mailServer.sendmail(from_address, to, io.getvalue())
def sendMessage(eTitle, mSubject, eFrom, eTo): message = MIMEText(mSubject, 'plain', 'utf-8') message['From'] = Header(eFrom, 'utf-8') message['To'] = Header(eTo, 'utf-8') message['Subject'] = Header(eTitle, 'utf-8') return message.as_string()
def expiration_reminder(self, cr, uid, erp_server_addr, context=None): ''' 证书过期提醒。 每天执行一次,检测当天到期的证书,给证书主人及其上级发送一封到期提醒邮件。 重复执行的设置钩子,在【设置】-【技术】-【自动化】-【安排的动作】里增加一条每天执行一次的动作。 设置需要一个参数,表示邮件里用于用户点击的链接。 另外,需要设置出去的邮件服务器. ''' log_line_head = "### zhengshu daoqi tixing: " exp_cers_ids = self.search(cr, uid, [("time", "=", time.strftime("%Y-%m-%d"))], context=context) exp_cers = self.browse(cr, uid, exp_cers_ids, context=context) dai_fa_song = {} # format: # {hr_employee.id: {obj: hr_employee # users: {hr_employee.id: {obj: hr_employee # cers: [nantian_erp.certificate] # } # } # } # } for cer in exp_cers: if not cer.employee_ids: continue user = cer.employee_ids mgr = None mgr_id = None if user.parent_id: mgr = user.parent_id mgr_id = mgr.id if not dai_fa_song.has_key(mgr_id): dai_fa_song[mgr_id] = {"obj": mgr, "users": {}} if not dai_fa_song[mgr_id]["users"].has_key(user.id): dai_fa_song[mgr_id]["users"][user.id] = { "obj": user, "cers": [] } dai_fa_song[mgr_id]["users"][user.id]['cers'].append(cer) failed_users = [] for mid, mgr in dai_fa_song.items(): users = mgr['users'] mgr = mgr['obj'] if mgr != None: if not mgr.work_email: failed_users.append(mgr) else: to_list = [ formataddr((Header(mgr.name_related, "utf8").encode(), mgr.work_email.encode("utf8"))) ] mail_content = u"<div>%s 您好:" \ u"<p>您的下属中有如下成员证书已经到期,特此提醒。</p>" \ u"<ol>%s</ol>" \ u"<p>详情请登录南天ERP查询:<a href='%s'>%s</a></p>" \ u"<p>南天电子</p></div>" \ %(mgr.name_related, "".join([u"<li>%s 证书【%s】到期时间 %s 。</li>" %(user['obj'].name_related, c.name, c.time) for user_id, user in users.items() for c in user["cers"]]), erp_server_addr, erp_server_addr) mail_mail = self.pool.get('mail.mail') mail_id = mail_mail.create( cr, uid, { 'body_html': mail_content, 'subject': Header(u'证书过期提醒', 'utf-8').encode(), 'email_to': to_list, 'auto_delete': True, }, context=context) print("%s sending to %s(%s)..." % (log_line_head, mgr.name_related, mgr.work_email)) mail_mail.send(cr, uid, [mail_id], context=context) for user_id, user in users.items(): cers = user['cers'] user = user['obj'] if not user.work_email: failed_users.append(user) continue to_list = [ formataddr((Header(user.name_related, "utf8").encode(), user.work_email.encode("utf8"))) ] mail_content = u"<div>%s 您好:" \ u"<p>您有如下证书已经到期:</p>" \ u"<ol>%s</ol>" \ u"<p>详情请登录南天ERP查询:<a href='%s'>%s</a></p>" \ u"<p>南天电子</p></div>" \ %(user.name_related, "".join([u"<li>%s 到期时间 %s</li>" % (c.name, c.time) for c in cers]), erp_server_addr, erp_server_addr) mail_mail = self.pool.get('mail.mail') mail_id = mail_mail.create( cr, uid, { 'body_html': mail_content, 'subject': Header(u'证书过期提醒', 'utf-8').encode(), 'email_to': to_list, 'auto_delete': True, }, context=context) print("%s sending to %s(%s)..." % (log_line_head, user.name_related, user.work_email)) mail_mail.send(cr, uid, [mail_id], context=context) if failed_users: print("%s send failed users(email is empty): %s items. [%s]" % (log_line_head, len(failed_users), ", ".join([ "%s(%s)" % (user.name_related, user.id) for user in failed_users ])))