ส่งเมลด้วยไพธอน หัดเขียน Python ส่งเมลผ่าน SMTP

ตอบกระทู้

รูปแสดงอารมณ์
:icon_plusone: :like: :plusone: :gfb: :-D :) :( :-o 8O :? 8) :lol: :x :P :oops: :cry: :evil: :twisted: :roll: :wink: :!: :?: :idea: :arrow: :| :mrgreen: :angry: :baa: :biggrin:
รูปแสดงอารมณ์อื่นๆ

BBCode เปิด
[img] เปิด
[url] เปิด
[Smile icon] เปิด

กระทู้แนะนำ
   

มุมมองที่ขยายได้ กระทู้แนะนำ: ส่งเมลด้วยไพธอน หัดเขียน Python ส่งเมลผ่าน SMTP

Re: ส่งเมลด้วยไพธอน หัดเขียน Python ส่งเมลผ่าน SMTP

โดย mindphp » 09/12/2019 8:55 pm

อีกตัวอย่างจากหนังสือ python 101

โค้ด: เลือกทั้งหมด

import os
import smtplib

from email import encoders
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.utils import formatdate

def send_email(email, pdf):
    """
    Send an email out
    """
    header0 = 'Content-Disposition'
    header1 ='attachment; filename="%s"' % os.path.basename(pdf)
    header = header0, header1
    
    host = "mail.server.com"
    server = smtplib.SMTP(host)
    subject = "Test email from Python"
    to = email
    from_addr = "[email protected]"
    body_text = "Here is the Alpha copy of Python 101, Part I"
    
    # create the message
    msg = MIMEMultipart()
    msg["From"] = from_addr
    msg["Subject"] = subject
    msg["Date"] = formatdate(localtime=True)
    msg["To"] = email
    
    msg.attach( MIMEText(body_text) )
    
    attachment = MIMEBase('application', "octet-stream")
    try:
        with open(pdf, "rb") as fh:
            data = fh.read()
        attachment.set_payload( data )
        encoders.encode_base64(attachment)
        attachment.add_header(*header)
        msg.attach(attachment)
    except IOError:
        msg = "Error opening attachment file %s" % file_to_attach
        print(msg)
        
    server.sendmail(from_addr, to, msg.as_string())
    
if __name__ == "__main__":
    send_email("[email protected]", "output/python101.pdf")

ส่งเมลด้วยไพธอน หัดเขียน Python ส่งเมลผ่าน SMTP

โดย mindphp » 25/07/2017 4:40 am

ส่งเมลด้วยไพธอน หัดเขียน #Python ส่งเมลด้วย #SMTP
สิ่งที่ต้องใช้คือ
1. โมดูล smtplib,email ถ้ายังไม่มีให้ติดตั้ง โมดูลเสริมกันก่อน ตามกระทู้นี้
https://www.mindphp.com/forums/viewtopic ... 44&t=38007
2. ข้อมูล Mail Server SMTP
SMTP Server:
SMTP Port:
Username:
Password:
เมื่อมีครบแล้วลงโค้ดกันเย
test_mindphp_smtp_mail.py

โค้ด: เลือกทั้งหมด

import email
import smtplib

msg = email.message_from_string('warning')
msg['From'] = "[email protected]"	# เมลผู้ส่ง
msg['To'] = "[email protected]" # เมลผู้รับ
msg['Subject'] = "Hi From mindphp.com"

s = smtplib.SMTP("smtp.live.com",465)
s.ehlo() # ชื่อต่อกับ Hostname 
s.starttls() # กำหนดใช้ใช้ SSL การติดต่อกับ SMTP server ด้วยโหมท TLS mode
s.ehlo()
s.login(msg['From'], 'pass')

s.sendmail(msg['From'], msg['To'], msg.as_string())

s.quit()

ข้างบน