本文目錄一覽:
- 1、如何在python中使用smtplib連接gmail發送郵件
- 2、如何使用Python發送帶的郵件
- 3、如何使用python發送各類郵件
- 4、如何在python程序中發郵件
- 5、如何用Python發郵件
- 6、如何通過python發送郵件啊?
如何在python中使用smtplib連接gmail發送郵件
單擊”工具”菜單,然後選擇”帳戶…”。
單擊”添加”,然後單擊”郵件…”
在”顯示名:”欄位中輸入您的姓名,然後單擊”下一步”。
在”電子郵件地址:”欄位中輸入您的完整 Gmail 電子郵件地址 (username@gmail.com),然後單擊”下一步”。
在”接收郵件(POP3, IMAP 或 HTTP)伺服器:”欄位中輸入”pop.gmail.com”。在”發送郵件伺服器 (SMTP):”欄位中輸入”smtp.gmail.com”。
單擊”下一步”。
在”帳戶名:”欄位中輸入您的 Gmail 用戶名(包括”@gmail.com”)。在”密碼:”欄位中輸入您的 Gmail 密碼,然後單擊”下一步”。
單擊”完成”。
突出顯示”帳戶”下的”pop.gmail.com”,並單擊”屬性”。
單擊”高級”標籤。
選中”發送郵件 (SMTP)”下”此伺服器要求安全連接 (SSL)”旁邊的複選框。
在”發送郵件 (SMTP):”欄位中輸入”465″。
選中”接收郵件 (POP3)”下”此伺服器要求安全連接 (SSL)”旁邊的複選框。此埠將更改為 995。
*”發送”和”接收”郵件伺服器欄位的順序因版本而異。確保您在每一欄位中輸入了正確信息。
如何使用Python發送帶的郵件
import smtplibfrom email import encodersfrom email.header import Headerfrom email.mime.text import MIMETextfrom email.utils import parseaddr, formataddrdef send_email(from_addr, to_addr, subject, password):
msg = MIMEText(“郵件正文”,’html’,’utf-8′)
msg[‘From’] = u’%s’ % from_addr
msg[‘To’] = u’%s’ % to_addr
msg[‘Subject’] = subject
smtp = smtplib.SMTP_SSL(‘smtp.163.com’, 465)
smtp.set_debuglevel(1)
smtp.ehlo(“smtp.163.com”)
smtp.login(from_addr, password)
smtp.sendmail(from_addr, [to_addr], msg.as_string())if __name__ == “__main__”:
# 這裡的密碼是開啟smtp服務時輸入的客戶端登錄授權碼,並不是郵箱密碼
# 現在很多郵箱都需要先開啟smtp才能這樣發送郵件
send_email(u”from_addr”,u”to_addr”,u”主題”,u”password”)
如何使用python發送各類郵件
以下代碼調試通過:
# coding: utf-8
import smtplib
from email.mime.text import MIMEText
from email.header import Header
sender = ‘lucia_gaga@139.com’
receiver = ‘lu.han@beebank.com’
subject = ‘python email test’
smtpserver = ‘smtp.139.com’
username = ‘lucia_gaga@139.com’
password = ‘xxxxxxxx’
msg = MIMEText(‘你好 lucia 這是你的第一封 python 發出的郵件’, ‘text’, ‘utf-8’)
# 中文需參數『utf-8’,單位元組字元不需要
msg[‘Subject’] = Header(subject, ‘utf-8’)
smtp = smtplib.SMTP()
smtp.connect(‘smtp.139.com’)
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()
運行效果:
如何在python程序中發郵件
通過命令行發送郵件,功能強大
python ./mail -s $server -f $from -t $to -u $user -p $pass -S “$subject” -m “${mail_msg}” -F $file
Python 發送郵件可以添加附件:
#!/usr/bin/python
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email import Utils, Encoders
import mimetypes, sys,smtplib,socket,getopt
class SendMail:
def __init__(self,smtp_server,from_addr,to_addr,user,passwd):
self.mailserver=smtp_server
self.from_addr=from_addr
self.to_addr=to_addr
self.username=user
self.password=passwd
def attachment(self,filename):
fd=open(filename,’rb’)
filename=filename.split(‘/’)
mimetype,mimeencoding=mimetypes.guess_type(filename[-1])
if (mimeencoding is None) or (mimetype is None):
mimetype=’application/octet-stream’
maintype,subtype=mimetype.split(‘/’)
if maintype==’text’:
retval=MIMEText(fd.read(), _subtype=subtype, _charset=’utf-8′)
else:
retval=MIMEBase(maintype,subtype)
retval.set_payload(fd.read())
Encoders.encode_base64(retval)
retval.add_header(‘Content-Disposition’,’attachment’,filename=filename[-1])
fd.close()
return retval
def msginfo(self,msg,subject,filename):
# message = “””Hello, ALL
#This is test message.
#–Anonymous”””
message=msg
msg=MIMEMultipart()
msg[‘To’] = self.to_addr
msg[‘From’] = ‘sa ‘+self.from_addr+”
msg[‘Date’] = Utils.formatdate(localtime=1)
msg[‘Message-ID’] = Utils.make_msgid()
if subject:
msg[‘Subject’] = subject
if message:
body=MIMEText(message,_subtype=’plain’)
msg.attach(body)
#for filename in sys.argv[1:]:
if filename:
msg.attach(self.attachment(filename))
return msg.as_string()
def send(self,msg=None,subject=None,filename=None):
try:
s=smtplib.SMTP(self.mailserver)
try:
s.login(self.username,self.password)
except smtplib.SMTPException,e:
print “Authentication failed:”,e
sys.exit(1)
s.sendmail(self.from_addr,self.to_addr.split(‘,’),self.msginfo(msg,subject,filename))
except (socket.gaierror,socket.error,socket.herror,smtplib.SMTPException),e:
print “*** Your message may not have been sent!”
print e
sys.exit(2)
else:
print “Message successfully sent to %d recipient(s)” %len(self.to_addr)
if __name__==’__main__’:
def usage():
print “””Useage:%s [-h] -s SMTP Server -f FROM_ADDRESS -t TO_ADDRESS -u USER_NAME -p PASSWORD [-S MAIL_SUBJECT -m MAIL_MESSAGE -F ATTACHMENT]
Mandatory arguments to long options are mandatory for short options too.
-f, –from= Sets the name of the “from” person (i.e., the envelope sender of the mail).
-t, –to= Addressee’s address. -t “test@test.com,test1@test.com”.
-u, –user= Login SMTP server username.
-p, –pass= Login SMTP server password.
-S, –subject= Mail subject.
-m, –msg= Mail message.-m “msg, …….”
-F, –file= Attachment file name.
-h, –help Help documen.
“”” %sys.argv[0]
sys.exit(3)
try:
options,args=getopt.getopt(sys.argv[1:],”hs:f:t:u:p:S:m:F:”,”–help –server= –from= –to= –user= –pass= –subject= –msg= –file=”,)
except getopt.GetoptError:
usage()
sys.exit(3)
server=None
from_addr=None
to_addr=None
username=None
password=None
subject=None
filename=None
msg=None
for name,value in options:
if name in (“-h”,”–help”):
usage()
if name in (“-s”,”–server”):
server=value
if name in (“-f”,”–from”):
from_addr=value
if name in (“-t”,”–to”):
to_addr=value
if name in (“-u”,”–user”):
username=value
if name in (“-p”,”–pass”):
password=value
if name in (“-S”,”–subject”):
subject=value
if name in (“-m”,”–msg”):
msg=value
if name in (“-F”,”–file”):
filename=value
if server and from_addr and to_addr and username and password:
test=SendMail(server,from_addr,to_addr,username,password)
test.send(msg,subject,filename)
else:
usage()
如何用Python發郵件
Python發送郵件簡單的實例:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import smtplib
from email.mime.text import MIMEText
from email.header import Header
sender = ‘from@runoob.com’
receivers = [‘429240967@qq.com’] # 接收郵件,可設置為你的QQ郵箱或者其他郵箱
# 三個參數:第一個為文本內容,第二個 plain 設置文本格式,第三個 utf-8 設置編碼
message = MIMEText(‘Python 郵件發送測試…’, ‘plain’, ‘utf-8’)
message[‘From’] = Header(“菜鳥教程”, ‘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: 無法發送郵件”
如何通過python發送郵件啊?
一般最好有個smtp伺服器,比如說你在163註冊個郵箱,這樣可以用smtplib通過這個郵箱來發送。以下是示例:
#-*- coding:utf8 -*-
import smtplib
import email
import mimetypes
from email.MIMEMultipart import MIMEMultipart
from email.mime.text import MIMEText
mail_host=”smtp.163.com”
mail_user=”yourusername”
mail_pass=”yourpassword”
mail_postfix=”mail.163.com”
def sendmail(to_list,sub,con):
“””發送郵件
“””
# translation
me = mail_user+””+mail_user+”@”+mail_postfix+””
msg = MIMEMultipart(‘related’)
msg[‘Subject’] = email.Header.Header(sub,’utf-8′)
msg[‘From’] = me
msg[‘To’] = “;”.join(to_list)
msg.preamble = ‘This is a multi-part message in MIME format.’
msgAlternative = MIMEMultipart(‘alternative’)
msgText = MIMEText(con, ‘plain’, ‘utf-8’)
msgAlternative.attach(msgText)
msg.attach(msgAlternative)
try:
s = smtplib.SMTP()
s.connect(mail_host)
s.login(mail_user,mail_pass)
s.sendmail(me, to_list, msg.as_string())
s.quit()
except Exception,e:
return False
return True
if __name__ == ‘__main__’:
if sendmail([‘test@test.com’],”測試”,”測試”):
print “Success!”
else:
print “Fail!”
如果要不經過郵件系統直接發,通常會被當作垃圾郵件扔了,所以還是這樣吧。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/241791.html