Python 3でメールを送る

2912 ワード


方法1自分のsmtpサーバを使用する
自分のサーバをsmtpサーバとして使用したい場合は、まず次のコマンドを実行します.
python3 -m smtpd -n -c DebuggingServer localhost:1025 &

メールを送信するコードも変更しなければなりません
server = smtplib.SMTP(host='smtp.gmail.com', port=1025)

メールを送信するコードは次のとおりです.
#!/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("chen", '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:       ")

 
方法2:サードパーティsmtpサーバの使用
import smtplib
from email.header import Header
from email.mime.text import MIMEText
 
#     SMTP   
mail_host = "smtp.163.com"   # SMTP   
mail_user = "[email protected]"         #    
mail_pass = "xxxxx"        #     ,     
 
sender = '[email protected]'  #      (    ,      )
receivers = ['[email protected]'] #     ,      QQ        
 
content = '  ,     '
title = 'Python  ' #     
 
def sendEmail():
 
  message = MIMEText(content, 'plain', 'utf-8') #   ,   ,   
  message['From'] = "{}".format(sender)
  message['To'] = ",".join(receivers)
  message['Subject'] = title
 
  try:
    smtpObj = smtplib.SMTP_SSL(mail_host, 465) #   SSL  ,      465
    smtpObj.login(mail_user, mail_pass) #     
    smtpObj.sendmail(sender, receivers, message.as_string()) #   
    print("mail has been send successfully.")
  except smtplib.SMTPException as e:
    print(e)
 
def send_email2(SMTP_host, from_account, from_passwd, to_account, subject, content):
  email_client = smtplib.SMTP(SMTP_host)
  email_client.login(from_account, from_passwd)
  # create msg
  msg = MIMEText(content, 'plain', 'utf-8')
  msg['Subject'] = Header(subject, 'utf-8') # subject
  msg['From'] = from_account
  msg['To'] = to_account
  email_client.sendmail(from_account, to_account, msg.as_string())
 
  email_client.quit()
 
if __name__ == '__main__':
  sendEmail()
  # receiver = '***'
  # send_email2(mail_host, mail_user, mail_pass, receiver, title, content)

参考記事:https://www.jb51.net/article/142192.htm
                  https://www.runoob.com/python3/python3-smtp.html