この記事では主に、Python でメールを送受信する機能を簡単に実装する方法を説明します。重要な知識は、Python の組み込みモジュールである Poplib と stmplib の使用です。一定の参考価値がありますので、興味のある方は参考にしていただければ幸いです。
1. 準備
まず、Sina Mailbox を使用して次の設定を行う必要があります:
Sina Mailbox ホームページの右上隅にある設定を見つけます。 >その他の設定 を選択し、左側の [Client/pop/imap/smtp] を選択します:
最後に、Pop3/smtp サービスのサービス ステータスをオンにします:
2。 mail
まず、poplib ログイン メールボックスとダウンロード メール用のインターフェイスをいくつか紹介します:
self.popHost = 'pop.sina.com' self.smtpHost = 'smtp.sina.com' self.port = 25 self.userName = 'xxxxxx@sina.com' self.passWord = 'xxxxxx' self.bossMail = 'xxxxxx@qq.com'
ログイン メールボックス、pop、smtp サーバー、およびポートを指定するには、上記のような定数が必要です。 Poplib の POP3_SSL インターフェイスを呼び出して、メールボックスにログインします。
# 登录邮箱 def login(self): try: self.mailLink = poplib.POP3_SSL(self.popHost) self.mailLink.set_debuglevel(0) self.mailLink.user(self.userName) self.mailLink.pass_(self.passWord) self.mailLink.list() print u'login success!' except Exception as e: print u'login fail! ' + str(e) quit()
メールにログインするときは、当然のことですが、ユーザー名とパスワードを入力する必要があります。上記のコードに示されているように、使い方は非常に簡単です。
メールボックスに正常にログインしたら、リストメソッドを使用してメールボックスのメール情報を取得できます。リスト メソッドの定義が表示されます:
def list(self, which=None): """Request listing, return result. Result without a message number argument is in form ['response', ['mesg_num octets', ...], octets]. Result when a message number argument is given is a single response: the "scan listing" for that message. """ if which is not None: return self._shortcmd('LIST %s' % which) return self._longcmd('LIST')
リスト メソッドのコメントが表示されます。中国語の意味は、リスト メソッドにはデフォルトのパラメータがあり、呼び出し元がパラメータを指定しない場合のデフォルト値は None であることを意味します。 、メソッドはすべての電子メールの情報をリストします。戻り形式は [response, ['msg_number, octets', ...], octets] です。response は応答結果、msg_number は電子メール番号、octets は8ビットのバイト単位。具体的な例を見てみましょう:
('+OK ', ['1 2424', '2 2422'], 16)
これは、list() メソッドを呼び出した後の戻り結果です。明らかに、これはタプルです。最初の値 sahib は、要求が成功したことを示す '+OK' で応答します。2 番目の値は、電子メール情報を格納する配列です。たとえば、「1 2424」の 1 は、電子メール番号が 1 であることを意味します。
poplib を使用してメールをダウンロードする方法を見てみましょう。
# 获取邮件 def retrMail(self): try: mail_list = self.mailLink.list()[1] if len(mail_list) == 0: return None mail_info = mail_list[0].split(' ') number = mail_info[0] mail = self.mailLink.retr(number)[1] self.mailLink.dele(number) subject = u'' sender = u'' for i in range(0, len(mail)): if mail[i].startswith('Subject'): subject = mail[i][9:] if mail[i].startswith('X-Sender'): sender = mail[i][10:] content = {'subject': subject, 'sender': sender} return content except Exception as e: print str(e) return None
poplib のメール内容を取得するインターフェースは retr メソッドです。パラメータが 1 つ必要で、それは取得する電子メール番号です。以下は retr メソッドの定義です:
def retr(self, which): """Retrieve whole message number 'which'. Result is in form ['response', ['line', ...], octets]. """ return self._longcmd('RETR %s' % which)
コメントを見ると、retr メソッドは指定された番号を持つメールの内容全体を取得でき、その戻り形式は [response, ['line', ...], オクテット], 返されたタプルの 2 番目の要素にメールの内容が格納されており、その格納形式が配列であることがわかります。この配列がどのようなものかをテストしてみましょう。
この配列の保存形式は dict に似ていることがわかります。したがって、これに基づいて興味のあるものを見つけることができます。たとえば、サンプル コードが電子メールの件名と送信者を検索するものである場合、上記のコードのように記述できます。もちろん、通常のマッチングを使用することもできます~~~ テスト結果は次のとおりです:
まあ... 自分で試してみることもできます。
3. 電子メールを送信する SMTP
POP と同様に、SMTP を使用する前にいくつかの必要な定数を指定する必要があります:
self.mail_box = smtplib.SMTP(self.smtpHost, self.port) self.mail_box.login(self.userName, self.passWord)
上記は、SMTP を使用してメールボックスにログインするためのコードです。ポップスに似ています。 smtp を使用して電子メールを送信するコードを以下に示します。Python がいかにシンプルで美しいかがわかります。
# 发送邮件 def sendMsg(self, mail_body='Success!'): try: msg = MIMEText(mail_body, 'plain', 'utf-8') msg['Subject'] = mail_body msg['from'] = self.userName self.mail_box.sendmail(self.userName, self.bossMail, msg.as_string()) print u'send mail success!' except Exception as e: print u'send mail fail! ' + str(e)
これはPythonでsmtpを使用してメールを送信するためのコードです!とても簡単です!とても便利!とても分かりやすいです!ここでの主な方法は sendmail で、送信者、受信者、電子メールの内容を指定するだけです。 MIMEText もあります。その定義は次のようになります。
class MIMEText(MIMENonMultipart): """Class for generating text/* type MIME documents.""" def __init__(self, _text, _subtype='plain', _charset='us-ascii'): """Create a text/* type MIME document. _text is the string for this message object. _subtype is the MIME sub content type, defaulting to "plain". _charset is the character set parameter added to the Content-Type header. This defaults to "us-ascii". Note that as a side-effect, the Content-Transfer-Encoding header will also be set. """ MIMENonMultipart.__init__(self, 'text', _subtype, **{'charset': _charset}) self.set_payload(_text, _charset)
コメントを参照してください~~~ これは、指定されたコンテンツと指定されたエンコーディングを持つ MIME ドキュメントを生成するための単なるメソッドです。さて、sendmail メソッドを見てみましょう~~~
def sendmail(self, from_addr, to_addrs, msg, mail_options=[], rcpt_options=[]): """This command performs an entire mail transaction. The arguments are: - from_addr : The address sending this mail. - to_addrs : A list of addresses to send this mail to. A bare string will be treated as a list with 1 address. - msg : The message to send. - mail_options : List of ESMTP options (such as 8bitmime) for the mail command. - rcpt_options : List of ESMTP options (such as DSN commands) for all the rcpt commands.
うーん... smtp を使用してメールを送信する方法は以上です。
4. ソースコードとテスト
# -*- coding:utf-8 -*- from email.mime.text import MIMEText import poplib import smtplib class MailManager(object): def __init__(self): self.popHost = 'pop.sina.com' self.smtpHost = 'smtp.sina.com' self.port = 25 self.userName = 'xxxxxx@sina.com' self.passWord = 'xxxxxx' self.bossMail = 'xxxxxx@qq.com' self.login() self.configMailBox() # 登录邮箱 def login(self): try: self.mailLink = poplib.POP3_SSL(self.popHost) self.mailLink.set_debuglevel(0) self.mailLink.user(self.userName) self.mailLink.pass_(self.passWord) self.mailLink.list() print u'login success!' except Exception as e: print u'login fail! ' + str(e) quit() # 获取邮件 def retrMail(self): try: mail_list = self.mailLink.list()[1] if len(mail_list) == 0: return None mail_info = mail_list[0].split(' ') number = mail_info[0] mail = self.mailLink.retr(number)[1] self.mailLink.dele(number) subject = u'' sender = u'' for i in range(0, len(mail)): if mail[i].startswith('Subject'): subject = mail[i][9:] if mail[i].startswith('X-Sender'): sender = mail[i][10:] content = {'subject': subject, 'sender': sender} return content except Exception as e: print str(e) return None def configMailBox(self): try: self.mail_box = smtplib.SMTP(self.smtpHost, self.port) self.mail_box.login(self.userName, self.passWord) print u'config mailbox success!' except Exception as e: print u'config mailbox fail! ' + str(e) quit() # 发送邮件 def sendMsg(self, mail_body='Success!'): try: msg = MIMEText(mail_body, 'plain', 'utf-8') msg['Subject'] = mail_body msg['from'] = self.userName self.mail_box.sendmail(self.userName, self.bossMail, msg.as_string()) print u'send mail success!' except Exception as e: print u'send mail fail! ' + str(e) if __name__ == '__main__': mailManager = MailManager() mail = mailManager.retrMail() if mail != None: print mail mailManager.sendMsg()
上記のコードは、まずメールボックスにログインし、最初のメールを取得して削除し、次にメールの件名と送信者を取得して印刷し、最後に送信します。成功したメール 別の BossMail メール アドレスを指定します。
テスト結果は次のとおりです:
上記のコードをコピーして自分で試してみてください
関連する推奨事項:
thinkphp は 163 を実装します。 QQメールボックス送受信メールメソッド_PHP
以上がPythonでメール送受信機能を簡単実装の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

pythonusesahybridapproach、コンコイリティレーショントビテコードと解釈を組み合わせて、コードコンピレッドフォームと非依存性bytecode.2)

keydifferencesは、「for」と「while "loopsare:1)" for "for" loopsareideal forterating overencesonownowiterations、while2) "for" for "for" for "for" for "for" for "for" for for for for "wide" loopsarebetterunuinguntinunuinguntinisisisisisisisisisisisisisisisisisisisisisisisisisisisations.un

Pythonでは、さまざまな方法でリストを接続して重複要素を管理できます。1)オペレーターを使用するか、すべての重複要素を保持します。 2)セットに変換してから、リストに戻ってすべての重複要素を削除しますが、元の順序は失われます。 3)ループを使用するか、包含をリストしてセットを組み合わせて重複要素を削除し、元の順序を維持します。

fasteStMethodDodforListConcatenationinpythOndontsonistize:1)forsmallLists、operatorisefficient.2)forlargerlists、list.extend()orlistcomlethingisfaster、withextend()beingmorememory-efficient bymodifyigniviselistinistin-place。

to insertelementsIntopeaseThonList、useappend()toaddtotheend、insert()foraspificposition、andextend()formultipleElements.1)useappend()foraddingsingleitemstotheend.2)useintert()toaddataspecificindex、cont'slowerforforgelists.3)

PythonListsareimplementedasdynamicarrays、notlinkedlists.1)they restorediguourmemoryblocks、それはパフォーマンスに影響を与えることに影響を与えます

pythonoffersfourmainmethodstoremoveelements fromalist:1)removesthefirstoccurrenceofavalue、2)pop(index(index(index)removes regvess returnsaspecifiedindex、3)delstatementremoveselementselementsbyindexorseLice、および4)clear()

toresolvea "許可denided" errors whenrunningascript、sofflowthesesteps:1)checkandadaddadaddadadaddaddadadadaddadaddadaddadaddaddaddaddaddadaddadaddaddaddaddadaddaddaddadadaddadaddadaddadadisionsisingmod xmyscript.shtomakeitexexutable.2)


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

SecLists
SecLists は、セキュリティ テスターの究極の相棒です。これは、セキュリティ評価中に頻繁に使用されるさまざまな種類のリストを 1 か所にまとめたものです。 SecLists は、セキュリティ テスターが必要とする可能性のあるすべてのリストを便利に提供することで、セキュリティ テストをより効率的かつ生産的にするのに役立ちます。リストの種類には、ユーザー名、パスワード、URL、ファジング ペイロード、機密データ パターン、Web シェルなどが含まれます。テスターはこのリポジトリを新しいテスト マシンにプルするだけで、必要なあらゆる種類のリストにアクセスできるようになります。

SAP NetWeaver Server Adapter for Eclipse
Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。

AtomエディタMac版ダウンロード
最も人気のあるオープンソースエディター

ドリームウィーバー CS6
ビジュアル Web 開発ツール

WebStorm Mac版
便利なJavaScript開発ツール
