Простой сервер SMTP (в Python)

попробуйте

 UIView.animate(withDuration: 1.0, animations: {
        self.titleLabel.textColor = UIColor(red:206/255, green: 206/255, blue: 206/255, alpha: 1.0)
        self.view.layoutIfNeeded()
    }
21
задан Filipp W. 22 May 2018 в 21:48
поделиться

4 ответа

Взгляните на этот SMTP-сервер приемника :

from __future__ import print_function
from datetime import datetime
import asyncore
from smtpd import SMTPServer

class EmlServer(SMTPServer):
    no = 0
    def process_message(self, peer, mailfrom, rcpttos, data):
        filename = '%s-%d.eml' % (datetime.now().strftime('%Y%m%d%H%M%S'),
                self.no)
        f = open(filename, 'w')
        f.write(data)
        f.close
        print('%s saved.' % filename)
        self.no += 1


def run():
    # start the smtp server on localhost:1025
    foo = EmlServer(('localhost', 1025), None)
    try:
        asyncore.loop()
    except KeyboardInterrupt:
        pass


if __name__ == '__main__':
    run()

Он использует smtpd.SMTPServer для сохранения писем в файлы.

41
ответ дан 16 October 2019 в 23:19
поделиться

Я также хотел запустить smtp сервер в Python и послать электронные письма с Python. Я хотел выполнить все это в веб-приложении Фляги в единственном процессе, что означает, что smtp сервер должен не блокироваться. Вот решение, я в конечном счете приехал в [ суть ]:

app.py

from flask import Flask, render_template
from smtp_client import send_email
from smtp_server import SMTPServer

app = Flask(__name__)

@app.route('/send_email')
def email():
  server = SMTPServer()
  server.start()
  try:
    send_email()
  finally:
    server.stop()
  return 'OK'

@app.route('/')
def index():
  return 'Woohoo'

if __name__ == '__main__':
  app.run(debug=True, host='0.0.0.0')

smtp_server.py

# smtp_server.py
import smtpd
import asyncore
import threading

class CustomSMTPServer(smtpd.SMTPServer):
  def process_message(self, peer, mailfrom, rcpttos, data):
    print('Receiving message from:', peer)
    print('Message addressed from:', mailfrom)
    print('Message addressed to:', rcpttos)
    print('Message length:', len(data))
    return

class SMTPServer():
  def __init__(self):
    self.port = 1025

  def start(self):
    '''Start listening on self.port'''
    # create an instance of the SMTP server, derived from  asyncore.dispatcher
    self.smtp = CustomSMTPServer(('0.0.0.0', self.port), None)
    # start the asyncore loop, listening for SMTP connection, within a thread
    # timeout parameter is important, otherwise code will block 30 seconds
    # after the smtp channel has been closed
    kwargs = {'timeout':1, 'use_poll': True}
    self.thread = threading.Thread(target=asyncore.loop, kwargs=kwargs)
    self.thread.start()

  def stop(self):
    '''Stop listening to self.port'''
    # close the SMTPserver to ensure no channels connect to asyncore
    self.smtp.close()
    # now it is safe to wait for asyncore.loop() to exit
    self.thread.join()

  # check for emails in a non-blocking way
  def get(self):
    '''Return all emails received so far'''
    return self.smtp.emails

if __name__ == '__main__':
  server = CustomSMTPServer(('0.0.0.0', 1025), None)
  asyncore.loop()

smtp_client.py

import smtplib
import email.utils
from email.mime.text import MIMEText

def send_email():
  sender='author@example.com'
  recipient='6142546977@tmomail.net'

  msg = MIMEText('This is the body of the message.')
  msg['To'] = email.utils.formataddr(('Recipient', recipient))
  msg['From'] = email.utils.formataddr(('Author', 'author@example.com'))
  msg['Subject'] = 'Simple test message'

  client = smtplib.SMTP('127.0.0.1', 1025)
  client.set_debuglevel(True) # show communication with the server
  try:
    client.sendmail('author@example.com', [recipient], msg.as_string())
  finally:
    client.quit()
[111 5] Затем запускает сервер с python app.py, и в другом запросе моделируют запрос к /send_email с curl localhost:5000/send_email. Обратите внимание, что для фактической отправки электронного письма (или SMS) необходимо будет перейти через другие обручи, детализированные здесь: https://blog.codinghorror.com/so-youd-like-to-send-some-email-through-code / .

0
ответ дан 16 October 2019 в 23:19
поделиться

На самом деле для отправки электронной почты требуются 2 вещи:

  • SMTP-сервер - это может быть либо Python SMTP-сервер , либо вы можете использовать GMail или сервер вашего интернет-провайдера. Скорее всего, вам не нужно запускать собственный.
  • Библиотека SMTP - что-то, что отправляет запрос по электронной почте на сервер SMTP. Python поставляется с библиотекой smtplib, которая может сделать это за вас. Здесь есть масса информации о том, как его использовать: http://docs.python.org/library/smtplib.html

Для чтения есть два варианта в зависимости от того, с какого сервера вы читаете письмо. .

21
ответ дан 16 October 2019 в 23:19
поделиться

Имеется SMTP-сервер Python .

Этот модуль предлагает несколько классов для реализации SMTP-серверов. Один из них - это общая реализация бездействия, которую можно переопределить, в то время как два других предлагают особые стратегии отправки почты.

1
ответ дан 16 October 2019 в 23:19
поделиться
Другие вопросы по тегам:

Похожие вопросы: