python_note
  • Introduction
  • My Python
    • Anaconda
    • argparse
    • datetime
    • json
    • logging
    • numpy
    • open
    • openCC
    • pandas & csv
    • Socket & SocketServer
    • re
    • yaml
    • smtp
    • 物件操作
    • unittest
    • 線程
    • prettytable
    • IO
    • pycurl
    • sys
    • pickle
    • auto-python-to-exe
    • cython
    • nuitka
  • Crawler
    • Urllib & Requests
      • User-agent
      • Percent-Encoding
      • mail code
    • Selenium
    • TCP & UDP
    • 控制字符(control character)
  • Web Development
    • Flask
      • RESTful api
      • Template
      • blueprint
    • Django
      • 環境佈署(windows)
    • 檢查Port
    • Apache
    • 使用者行為
    • jQuery
    • 壓力測試
    • DataTable
    • Bootstrap
    • CSS
    • JavaScript
    • Chart.js
  • Deep Learning
    • Keras 設定
    • RNN
    • LSTM
  • Test
    • T-Test
  • 資料結構
    • Hash
    • 時間複雜度
  • NLP
    • N-gram
    • CKIP
    • 中文轉數字
    • CRF
    • Mutual Information
    • 模糊比對
  • Linebot
    • Heroku
    • 圖文選單
    • channel
  • Linux
    • 常用指令
    • shell script
    • sshfs
    • ssh
    • nodejs & npm
    • debug
  • GCP
    • app engine
    • ssh(gcp)
    • gsutil
    • brabrabra
    • Load Balancer
    • k8s
  • Database
    • mysql
    • elasticsearch
      • Query
      • Backup and Restore
      • elasticdump
      • es2csv
      • ELK
    • mongodb
      • install
      • authentication
      • pymongo
    • sql server
  • go
    • Swarm
  • Docker
    • Kitematic
    • Dockerfile
    • Swarm
  • Git
  • 其他
    • USB軟體保護
    • Windows效能監視器
  • Blockchain
Powered by GitBook
On this page

Was this helpful?

  1. My Python

smtp

如何用python寄gmail

寄信者的google帳號需啟動低安全性應用程式存取權 (google帳戶 -> 登入和安全性 -> 具有帳戶存取權的應用程式)

如果有設定雙驗證則無法開啟上述存取權,建議可以直接開個新google帳號

若建立smtplib.SMTP_SSL連線時完全無回應的話可能與網路環境有關(在公司網路不行,筆電+手機網路就可以惹)

import smtplib
from email.mime.text import MIMEText

gmail_user = '123@gmail.com' # 寄信者
gmail_password = '123' # 寄信者密碼

msg = MIMEText('content')  # 信件內容
msg['Subject'] = 'Test'  # 信件標題
msg['From'] = gmail_user  # 寄信者
msg['To'] = '456@gmail.com'  # 收信者

server = smtplib.SMTP_SSL('smtp.gmail.com', 465)  # 不要亂改ㄛ
server.ehlo()
server.login(gmail_user, gmail_password)
server.sendmail(gmail_user, '456@gmail.com', msg.as_string())
server.quit()

print('Email sent!')

也可把SMTP_SSL改成SMTP連線,但就要調整其他設定惹還沒試成功

附加檔案

from email.mime.text import MIMEText

filename = "text.txt"
f = file(filename)
attachment = MIMEText(f.read())
attachment.add_header('Content-Disposition', 'attachment', filename=filename)           
msg.attach(attachment)
PreviousyamlNext物件操作

Last updated 5 years ago

Was this helpful?

參考連結: smtp_ssl

smtp

https://amoshyc.github.io/blog/2018/sending-gmail-in-python.html#注意事項
https://self.jxtsai.info/2016/09/python_22.html
https://codeday.me/bug/20180210/131030.html