Python は SMTP を使用して電子メールを送信します。
SMTP (Simple Mail Transfer Protocol) は、送信元アドレスから宛先アドレスへ電子メールを送信するための一連のルールです。文字の流れ。
Python の smtplib は、電子メールを送信するための非常に便利な方法を提供します。これは単に SMTP プロトコルをカプセル化するだけです。
SMTP オブジェクトを作成するための Python の構文は次のとおりです:
import smtplib smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
パラメータの説明:
host: SMTP サーバーのホスト。 w3cschool.cc のように、ホストの IP アドレスまたはドメイン名を指定できます。これはオプションのパラメーターです。
port: host パラメーターを指定する場合、SMTP サービスで使用されるポート番号を指定する必要があります。通常、SMTP ポート番号は 25 です。
local_hostname: SMTP がローカル マシン上にある場合は、サーバー アドレスを localhost として指定するだけで済みます。
Python SMTP オブジェクトは、sendmail メソッドを使用して電子メールを送信します。構文は次のとおりです。
SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]
from_addr: 電子メール送信者アドレス。
to_addrs: 文字列リスト、メール送信アドレス。
msg: メッセージを送信します
ここの 3 番目のパラメーターに注意してください。msg は電子メールを表す文字列です。一般に、メールはタイトル、送信者、受信者、メールの内容、添付ファイルなどで構成されていることがわかります。メールを送信するときは、メッセージの形式に注意してください。この形式は、smtp プロトコルで定義されている形式です。
例
以下は、Python を使用して電子メールを送信する簡単な例です:
#!/usr/bin/pythonimport smtplib sender = 'from@fromdomain.com'receivers = ['to@todomain.com']message = """From: From Person <from@fromdomain.com> To: To Person <to@todomain.com> Subject: SMTP e-mail test This is a test e-mail message. """try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, receivers, message) print "Successfully sent email"except SMTPException: print "Error: unable to send email"
Python を使用して HTML 形式で電子メールを送信する
HTML 形式で電子メールを送信することと、Python でプレーン テキスト メッセージを送信することの違いは次のとおりです。 _ サブタイプへの MIMEText は html に設定されます。具体的なコードは次のとおりです:
import smtplib from email.mime.text import MIMEText mailto_list=["YYY@YYY.com"] mail_host="smtp.XXX.com" #设置服务器mail_user="XXX" #用户名mail_pass="XXXX" #口令 mail_postfix="XXX.com" #发件箱的后缀 def send_mail(to_list,sub,content): #to_list:收件人;sub:主题;content:邮件内容 me="hello"+"<"+mail_user+"@"+mail_postfix+">" #这里的hello可以任意设置,收到信后,将按照设置显示 msg = MIMEText(content,_subtype='html',_charset='gb2312') #创建一个实例,这里设置为html格式邮件 msg['Subject'] = sub #设置主题 msg['From'] = me msg['To'] = ";".join(to_list) try: s = smtplib.SMTP() s.connect(mail_host) #连接smtp服务器 s.login(mail_user,mail_pass) #登陆服务器 s.sendmail(me, to_list, msg.as_string()) #发送邮件 s.close() return True except Exception, e: print str(e) return False if __name__ == '__main__': if send_mail(mailto_list,"hello","<a href='http://www.cnblogs.com/xiaowuyi'>小五义</a>"): print "发送成功" else: print "发送失败"
または、次の例に示すように、メッセージ本文で Content-type を text/html として指定することもできます:
#!/usr/bin/pythonimport smtplib message = """From: From Person <from@fromdomain.com> To: To Person <to@todomain.com> MIME-Version: 1.0 Content-type: text/html Subject: SMTP HTML e-mail test This is an e-mail message to be sent in HTML format <b>This is HTML message.</b> <h1 id="This-nbsp-is-nbsp-headline">This is headline.</h1> """try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, receivers, message) print "Successfully sent email"except SMTPException: print "Error: unable to send email"
Python は添付ファイル付きのメールを送信します
メールを送信するには添付ファイルを使用する場合は、最初に MIMEMultipart( ) インスタンスを作成し、次に添付ファイルを構築する必要があります。複数の添付ファイルがある場合は、それらを順番に構築し、最後に smtplib.smtp を使用して送信できます。
from email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartimport smtplib#创建一个带附件的实例msg = MIMEMultipart()#构造附件1att1 = MIMEText(open('d:\\123.rar', 'rb').read(), 'base64', 'gb2312')att1["Content-Type"] = 'application/octet-stream'att1["Content-Disposition"] = 'attachment; filename="123.doc"'#这里的filename可以任意写,写什么名字,邮件中显示什么名字msg.attach(att1)#构造附件2att2 = MIMEText(open('d:\\123.txt', 'rb').read(), 'base64', 'gb2312')att2["Content-Type"] = 'application/octet-stream'att2["Content-Disposition"] = 'attachment; filename="123.txt"'msg.attach(att2)#加邮件头msg['to'] = 'YYY@YYY.com'msg['from'] = 'XXX@XXX.com'msg['subject'] = 'hello world'#发送邮件try: server = smtplib.SMTP() server.connect('smtp.XXX.com') server.login('XXX','XXXXX')#XXX为用户名,XXXXX为密码 server.sendmail(msg['from'], msg['to'],msg.as_string()) server.quit() print '发送成功'except Exception, e: print str(e)
以下实例指定了Content-type header 为 multipart/mixed,并发送/tmp/test.txt 文本文件:
#!/usr/bin/pythonimport smtplibimport base64 filename = "/tmp/test.txt"# 读取文件内容并使用 base64 编码fo = open(filename, "rb")filecontent = fo.read()encodedcontent = base64.b64encode(filecontent) # base64sender = 'webmaster@tutorialpoint.com'reciever = 'amrood.admin@gmail.com'marker = "AUNIQUEMARKER"body =""" This is a test email to send an attachement. """# 定义头部信息part1 = """From: From Person <me@fromdomain.net> To: To Person <amrood.admin@gmail.com> Subject: Sending Attachement MIME-Version: 1.0 Content-Type: multipart/mixed; boundary=%s --%s """ % (marker, marker)# 定义消息动作part2 = """Content-Type: text/plain Content-Transfer-Encoding:8bit %s --%s """ % (body,marker)# 定义附近部分part3 = """Content-Type: multipart/mixed; name=\"%s\" Content-Transfer-Encoding:base64 Content-Disposition: attachment; filename=%s %s --%s-- """ %(filename, filename, encodedcontent, marker)message = part1 + part2 + part3try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, reciever, message) print "Successfully sent email"except Exception: print "Error: unable to send email"
【相关推荐】
5. php smtp发送邮件
7. python smtplib模块发送SSL/TLS安全邮件实例
以上がSMTP を使用して電子メールを送信する Python の詳細な紹介の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

Arraysinpython、特にvianumpy、arecrucialinscientificComputing fortheirefficienty andversitility.1)彼らは、fornumericaloperations、data analysis、andmachinelearning.2)numpy'simplementation incensuresfasteroperationsthanpasteroperations.3)arayableminablecickick

Pyenv、Venv、およびAnacondaを使用して、さまざまなPythonバージョンを管理できます。 1)Pyenvを使用して、複数のPythonバージョンを管理します。Pyenvをインストールし、グローバルバージョンとローカルバージョンを設定します。 2)VENVを使用して仮想環境を作成して、プロジェクトの依存関係を分離します。 3)Anacondaを使用して、データサイエンスプロジェクトでPythonバージョンを管理します。 4)システムレベルのタスク用にシステムPythonを保持します。これらのツールと戦略を通じて、Pythonのさまざまなバージョンを効果的に管理して、プロジェクトのスムーズな実行を確保できます。

numpyarrayshaveveraladvantages-averstandardpythonarrays:1)thealmuchfasterduetocベースのインプレンテーション、2)アレモレメモリ効率、特にlargedatasets、および3)それらは、拡散化された、構造化された形成術科療法、

パフォーマンスに対する配列の均一性の影響は二重です。1)均一性により、コンパイラはメモリアクセスを最適化し、パフォーマンスを改善できます。 2)しかし、タイプの多様性を制限し、それが非効率につながる可能性があります。要するに、適切なデータ構造を選択することが重要です。

craftexecutablepythonscripts、次のようになります

numpyarraysarasarebetterfornumeroperations andmulti-dimensionaldata、whilethearraymoduleissuitable forbasic、1)numpyexcelsinperformance and forlargedatasentassandcomplexoperations.2)thearraymuremememory-effictientivearientfa

NumPyArraySareBetterforHeavyNumericalComputing、whilethearrayarayismoreSuitableformemory-constrainedprojectswithsimpledatatypes.1)numpyarraysofferarays andatiledance andpeperancedatasandatassandcomplexoperations.2)thearraymoduleisuleiseightweightandmemememe-ef

ctypesallowsinging andmanipulatingc-stylearraysinpython.1)usectypestointerfacewithclibrariesforperformance.2)createc-stylearraysfornumericalcomputations.3)passarraystocfunctions foreffientientoperations.how、how、becuutiousmorymanagemation、performanceo


ホットAIツール

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

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

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

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

人気の記事

ホットツール

EditPlus 中国語クラック版
サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

Dreamweaver Mac版
ビジュアル Web 開発ツール

メモ帳++7.3.1
使いやすく無料のコードエディター

MantisBT
Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。

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

ホットトピック









