python實現電子郵件(E mail)傳送

2021-06-06 11:20:07 字數 1662 閱讀 9240

前幾天需要服務端傳送郵件的指令碼,發現直接用sendmail相對來說複雜,大才小用了,因為我只需要乙個傳送的功能即可。於是查查改改,很容易弄了乙個。

python弄這些簡單的email client,http client, tcp client之類的真的很方便,而且windows上也可以直接執行。

# import smtplib for the actual sending function

import sys

import getopt

import smtplib

sender = 'sender@***x'

# if there are more than one receiver, you need to ganerate a list.

# receiver = ['a@***x','b@***x']

receiver = ['receiver@***x']

server = 'smtp.mail.***x.cn'

port = '25'

pwd = 'password'

commaspace = ', '

# import the email modules we'll need

from email.mime.text import mimetext

def usage():

usagestr = '''usage: sendemail -c mail_content'''

print usagestr

def main(argv):

# get the email content in the "-c" argv

try:

opts, args = getopt.getopt(argv, "c:")

except getopt.getopterror:

usage()

sys.exit(2)

content = ''

for opt, arg in opts:

if opt == '-c':

content = arg

print content

msg = mimetext(content)

msg['subject'] = 'this is the subject'

msg['from'] = sender

msg['to'] = commaspace.join(receiver)

s = smtplib.smtp(server, port)

s.ehlo()

s.login(sender, pwd)

s.sendmail(sender, receiver, msg.as_string())

s.quit()

if __name__=="__main__":

main(sys.argv[1:])

python版本比較老時會遇到這種報錯:

importerror: no module named mime.text

解決辦法:

將這句from email.mime.text import mimetext

改為:from email.mimetext import mimetext

from email.header import header

python電子郵件 Python傳送電子郵件

smtp是傳送郵件的協議,python內建對smtp的支援 smtplib模組和email模組 可以傳送純文字郵件 html郵件以及帶附件的郵件 python的smtplib提供了一種很方便的途徑傳遞電子郵件,對smtp進行了簡單的封裝 傳送純文字郵件 匯入smtplib模組 from smtpli...

Python傳送電子郵件

源 sendemail.py import smtplib from email.mime.text import mimetext msg mimetext the body of the email is here 這裡是你的信件中的內容 msg from ltoddy 163.com 這裡是傳...

python 傳送電子郵件

from smtplib import smtp from email.header import header from email.mime.text import mimetext 傳送郵件 def send email 請自行修改下面的郵件傳送者和接收者 sender abcdefg 126...