The SMTP abbreviated python3

In this statement: This article is an excerpt made in learning to learn https://www.runoob.com/python3/python3-multithreading.html Simple Mail Transfer Protocol.

SMTP (Simple Mail Transfer Protocol) i.e., Simple Mail Transfer Protocol: it is a set of rules for transmitting from the source address to the destination address of the message, the relay controlled letters.

Create an SMTP object Syntax:
  Import smtplib
  smtpobj smtplib.SMTP = ([Host [, Port [, as local_hostname]]])
Parameters:
  Host: SMTP server host, the host can specify the ip address or domain name such as: runoob.com, this It is an optional parameter.
  port: If you provide a host parameters, you need to specify the port number used by the SMTP service, under normal circumstances SMTP port number is 25.
  local_hostname: If the SMTP on your local machine, you only need to specify the server address is localhost.

The method of the SMTP mail:
  SMTP.sendmail (from_addr, to_addrs, MSG [, mail_options, rcpt_options]
Parameters:
  from_addr: mail sender address.
  To_addrs: list of strings, the message being sent to the address.
  MSG: Send Message: string that represents the mail, usually consists of header, sender, message content, attachments, etc., must strictly follow the format defined format smtp protocol.

Example:

1, the conventional example:

  #! / usr / bin / python3
  # Some feature pack to import
  Import smtplib
  from email.mime.text Import MimeText
  from email.header Import Header # If the machine does sendmail access, you need to use a third-party SMTP service   # mail_host = " smtp.XXX.com "# settings server   # mail_user =" XXXX "# username   # mail_pass =" XXXXXX "# password   sender = '[email protected]' # sender   receivers = [ '[email protected]'] # mail to be sent, if multiple, separated by commas. # Three parameters: the first one of the text, the second set plain text format (html format if it is to send it directly into 'html', then the first parameter (the text) into html format on the line ), the third set utf-8 encoded   message = MIMEText ( 'Python sending test messages ...', 'Plain', 'utf-8')   # standard mail header information required three: from, to, subject, each line segmentation information directly empty   message [ 'From'] = Header ( " novice tutorial", 'utf-8'

  






  





  subject = 'Python SMTP Mail test' #subject is not there 'test' keywords, otherwise it will be considered spam.
  Message [ 'the Subject'] = Header (Subject, 'UTF-. 8')

  the try: # SMTP service when using a third-party, need to be connected, a login operation     #smtpObj smtplib.SMTP = ()     # smtpObj.connect (mail_host, 25)     # smtpObj.login (mail_user, mail_pass) # If you log in using the authorization code third-party mail client, the password here (mail_pass) using the authorization code     smtpObj = smtplib.SMTP ( 'localhost') # create Object     smtpObj.sendmail (sender , receivers, message.as_string ()) # E-mail, message.as_string (): string     after print ( "mail transmission success") if the unit has installed # sendmail, then the output will be directly executed successfully sent successfully.   smtplib.SMTPException the except:     Print ( "Error: Can not Send Mail")
    








2, examples of messages with attachments sent:

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

  sender = '[email protected]'
  receivers = ['[email protected]'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

  #创建一个带附件的实例
  message = MIMEMultipart()
  message['From'] = Header("菜鸟教程", 'utf-8')
  message['To'] = Header("测试", 'utf-8')
  subject = 'Python SMTP 邮件测试'
  message['Subject'] = Header(subject, 'utf-8')

  #邮件正文内容
  message.attach(MIMEText('这是菜鸟教程Python 邮件发送测试……', 'plain', 'utf-8'))

  # 构造附件1,传送当前目录下的test.txt文件,如果不在当前目录下是不能这样构建,按构建附件2的方式即可。
  #另外,这样子会将test.txt 文件的内容读取转换成文本发送出去,改成使用 MIMEApplication 就正常发送附件了。
  #{
  # from email.mime.application import MIMEApplication
  # att1 = MIMEApplication(open('test.txt', 'rb').read())
  #}
  att1 = MIMEText(open('test.txt', 'rb').read(), 'base64', 'utf-8')

  att1["Content-Type"] = 'application/octet-stream'
  # 这里的filename可以任意写,写什么名字,邮件中显示什么名字
  att1["Content-Disposition"] = 'attachment; filename="test.txt"'
  message.attach(att1)

  # 构造附件2,指定文件的路径的方式
  path='D:/test/test.txt'
  file=open(path,'rb')
  att2=MIMEText(file.read(),'base64','utf-8')

  att2["Content-Type"] = 'application/octet-stream'
  att2["Content-Disposition"] = 'attachment; filename="runoob.txt"'
  message.attach(att2)

  try:
    smtpObj = smtplib.SMTP('localhost')
    smtpObj.sendmail(sender, receivers, message.as_string())
    print ("邮件发送成功")
  except smtplib.SMTPException:
    print ("Error: 无法发送邮件")

3、使用第三方smtp服务发送邮件的实例:

  #!/usr/bin/python3

  import smtplib
  from email.mime.text import MIMEText
  from email.utils import formataddr

  my_sender='[email protected]' # 发件人邮箱账号
  my_pass = 'xxxxxxxxxx' # 发件人邮箱密码
  my_user='[email protected]' # 收件人邮箱账号,我这边发送给自己
  def mail():
    ret=True
    try:
      msg=MIMEText('填写邮件内容','plain','utf-8')
      msg['From']=formataddr(["FromRunoob",my_sender]) # 括号里的对应发件人邮箱昵称、发件人邮箱账号
      msg['To']=formataddr(["FK",my_user]) # 括号里的对应收件人邮箱昵称、收件人邮箱账号
      msg['Subject']="菜鸟教程发送邮件测试" # 邮件的主题,也可以说是标题

      server=smtplib.SMTP_SSL("smtp.qq.com", 465) # 发件人邮箱中的SMTP服务器,端口是25
      server.login(my_sender, my_pass) # 括号中对应的是发件人邮箱账号、邮箱密码
      server.sendmail(my_sender,[my_user,],msg.as_string()) # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
      server.quit() # 关闭连接
    except Exception: # 如果 try 中的语句没有执行,则会执行下面的 ret=False
      ret=False
    return ret
  ret=mail()
  if ret:
    print("邮件发送成功")
  else:
    print("邮件发送失败")

Guess you like

Origin www.cnblogs.com/yangrongkuan/p/12116662.html