發送電子郵件的技巧 📧 (Mail Sending Tricks)

2022-03-02

說明如何使用 PowerShell 寄送電子郵件以及用 Windows Run 建立電子郵件的技巧。

logo

說明

Mail with PowerShel

可以指定 Mail Server 的方式來使用 PowerShell 寄送電子郵件,使用 BodyAsHtml 可以調整是否使用 Html 作為傳送內容,非常方便。

 Send-MailMessage 
 -From "sdwh <[email protected]>" 
 -To "user <[email protected]>" 
 -Subject "Mail" 
 -SmtpServer "[email protected]" 
 -Body "<h1>Hello World</h1>" 
 -BodyAsHtml

Mail with Windows Run

嚴格來說不是透過 Windows Run 去寄信,只是透過 Windows Run 把預設的電子郵件軟體開啟,並新建一封郵件帶入收件人、主題與內容。可以使用 Query Parameter 設定 Subject 以及 Body

Win + R

mailto:[email protected]?subject=Mail&body=Hello World

Mail with Python

說明如何使用 Python 使用 Rich Text 格式寄送電子郵件以及附件。

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

def renderMessage(content, receivers):
  mail = MIMEMultipart("alternative")
  mail['From'] = 'MailSystem <[email protected]>'
  mail["Subject"] = f'{now.year}-{now.month} Mail'
  mail["To"] = ', '.join([r for r in receivers])
  mail["CC"] = '[email protected]'

  partText = MIMEText(content, "html", "utf-8")
  mail.attach(partText)

  filename = f'{now.year}-{now.month}.csv'
  partAttach = MIMEApplication(open('PokeData.csv','rb').read())
  partAttach.add_header(
    'Content-Disposition',
    'attachment',
    filename = filename
  )
  mail.attach(partAttach)

  return mail.as_string().encode('ascii')
receivers = ['[email protected]', '[email protected]']
content = f'<p style="color:teal">Hello World</p>'

smtpObj = smtplib.SMTP('sdwh.dev', 25)
smtpObj.sendmail(
  '[email protected]', 
  receivers, 
  renderMessage(content, receivers)
)