Latest web development tutorials

Python3 SMTP per inviare la posta

SMTP (Simple Mail Transfer Protocol) che è Simple Mail Transfer Protocol, che è un insieme di regole per la trasmissione di messaggi dalla sorgente alla destinazione, che deve controllare il modo in cui le lettere di transito.

smtplib di Python fornisce un modo molto conveniente per inviare e-mail. Si protocollo SMTP per un pacchetto semplice.

Python creare sintassi dell'oggetto SMTP è la seguente:

import smtplib

smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )

Descrizione Parametro:

  • ospiterà: host server SMTP. È possibile specificare un nome indirizzo IP dell'host o dominio come: w3cschool.cc, questo è un parametro opzionale.
  • porto: Se si fornisce un parametro host, è necessario specificare il numero della porta utilizzata dal servizio SMTP, in circostanze normali, il numero di porta SMTP è 25.
  • local_hostname: Se il vostro SMTP su questa macchina, è solo bisogno di specificare l'indirizzo del server per localhost.

Python oggetto SMTP utilizzando il metodo sendmail di invio di e-mail con la seguente sintassi:

SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]

Descrizione Parametro:

  • from_addr: indirizzo e-mail del mittente.
  • to_addrs: lista di stringhe, inviare e-mail.
  • msg: Invia un messaggio

Qui dobbiamo notare che il terzo argomento, MSG è una stringa che rappresenta la posta. Sappiamo che un messaggio è generalmente composto da un colpo di testa, mittente, destinatario, il contenuto del messaggio, allegati, ecc, inviare una mail, prestare attenzione al formato MSG. Questo formato è formato di definizione del protocollo SMTP.

Esempi

Quanto segue è un messaggio inviato utilizzando Python semplice esempio:

#!/usr/bin/python3

import smtplib
from email.mime.text import MIMEText
from email.header import Header

sender = '[email protected]'
receivers = ['[email protected]']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

# 三个参数:第一个为文本内容,第二个 plain 设置文本格式,第三个 utf-8 设置编码
message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8')
message['From'] = Header("本教程", 'utf-8')
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: 无法发送邮件")

Usiamo tre citazioni per impostare messaggi di posta elettronica, standard di e-mail richiede treintestazioni:Da, A eOggetto,ogni informazioni direttamente con una ripartizione riga vuota.

Siamo collegati istanziando oggettismtpObjaccesso modulo smtplib SMTP SMTP, e per inviare il messaggio utilizzando il metodosendmail.

Eseguire la procedura di cui sopra, se si installa questa unità sendmail, il risultato sarà:

$ python3 test.py 
邮件发送成功

Guarda la casella di posta elettronica (di solito nel cestino), è possibile visualizzare il messaggio di posta elettronica:

Se non abbiamo accesso nativo a sendmail, è possibile utilizzare anche altri fornitori di servizi di accesso SMTP (QQ, Netease, Google, ecc).

#!/usr/bin/python3

import smtplib
from email.mime.text import MIMEText
from email.header import Header

# 第三方 SMTP 服务
mail_host="smtp.XXX.com"  #设置服务器
mail_user="XXXX"    #用户名
mail_pass="XXXXXX"   #口令 


sender = '[email protected]'
receivers = ['[email protected]']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8')
message['From'] = Header("本教程", 'utf-8')
message['To'] =  Header("测试", 'utf-8')

subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')


try:
    smtpObj = smtplib.SMTP() 
    smtpObj.connect(mail_host, 25)    # 25 为 SMTP 端口号
    smtpObj.login(mail_user,mail_pass)
    smtpObj.sendmail(sender, receivers, message.as_string())
    print ("邮件发送成功")
except smtplib.SMTPException:
    print ("Error: 无法发送邮件")

Utilizzando Python messaggi inviati in formato HTML

Tranne messaggi inviati Python e messaggio di posta elettronica in formato HTML vengono inviati come testo normale nelle MIMEText _subtype impostato su HTML. codice specifico come segue:

#!/usr/bin/python3

import smtplib
from email.mime.text import MIMEText
from email.header import Header

sender = '[email protected]'
receivers = ['[email protected]']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

mail_msg = """
<p>Python 邮件发送测试...</p>
<p><a href="http://www.w3big.com">这是一个链接</a></p>
"""
message = MIMEText(mail_msg, 'html', 'utf-8')
message['From'] = Header("本教程", 'utf-8')
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: 无法发送邮件")

Eseguire la procedura di cui sopra, se si installa questa unità sendmail, il risultato sarà:

$ python3 test.py 
邮件发送成功

Guarda la casella di posta elettronica (di solito nel cestino), è possibile visualizzare il messaggio di posta elettronica:


Python inviare mail con allegati

Inviare messaggi con allegati, è necessario creare prima istanza MimeMultipart (), allegato poi costruito, se ci sono più allegati può essere costruito in modo sequenziale. Infine smtplib.smtp inviato.

#!/usr/bin/python3

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header

sender = '[email protected]'
receivers = ['[email protected]']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

#创建一个带附件的实例
message = MIMEMultipart()
message['From'] = Header("本教程", 'utf-8')
message['To'] =  Header("测试", 'utf-8')
subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')

#邮件正文内容
message.attach(MIMEText('这是本教程Python 邮件发送测试……', 'plain', 'utf-8'))

# 构造附件1,传送当前目录下的 test.txt 文件
att1 = MIMEText(open('test.txt', 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
# 这里的filename可以任意写,写什么名字,邮件中显示什么名字
att1["Content-Disposition"] = 'attachment; filename="test.txt"'
message.attach(att1)

# 构造附件2,传送当前目录下的 w3big.txt 文件
att2 = MIMEText(open('w3big.txt', 'rb').read(), 'base64', 'utf-8')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename="w3big.txt"'
message.attach(att2)

try:
    smtpObj = smtplib.SMTP('localhost')
    smtpObj.sendmail(sender, receivers, message.as_string())
    print ("邮件发送成功")
except smtplib.SMTPException:
    print ("Error: 无法发送邮件")
$ python3 test.py 
邮件发送成功

Guarda la casella di posta elettronica (di solito nel cestino), è possibile visualizzare il messaggio di posta elettronica:


Aggiungi una foto in testo HTML

messaggio di testo HTML nei fornitori di servizi di posta generali per aggiungere di fuori della catena non è valido, il diritto di aggiungere svolta sono riportati di seguito:

#!/usr/bin/python3

import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header

sender = '[email protected]'
receivers = ['[email protected]']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

msgRoot = MIMEMultipart('related')
msgRoot['From'] = Header("本教程", 'utf-8')
msgRoot['To'] =  Header("测试", 'utf-8')
subject = 'Python SMTP 邮件测试'
msgRoot['Subject'] = Header(subject, 'utf-8')

msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)


mail_msg = """
<p>Python 邮件发送测试...</p>
<p><a href="http://www.w3big.com">本教程链接</a></p>
<p>图片演示:</p>
<p><img src="cid:image1"></p>
"""
msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8'))

# 指定图片为当前目录
fp = open('test.png', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()

# 定义图片 ID,在 HTML 文本中引用
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)

try:
    smtpObj = smtplib.SMTP('localhost')
    smtpObj.sendmail(sender, receivers, msgRoot.as_string())
    print ("邮件发送成功")
except smtplib.SMTPException:
    print ("Error: 无法发送邮件")
$ python3 test.py 
邮件发送成功

Guarda la casella di posta elettronica (se nella spazzatura potrebbe essere necessario passare alla cartella Posta in arrivo prima che il display normale), è possibile visualizzare il messaggio di posta elettronica:

Per ulteriori informazioni, si prega di fare riferimento a: https://docs.python.org/3/library/email-examples.html .