SoFunction
Updated on 2024-10-29

Python3 realize send QQ mail function (attachment)

In this article, we share the example of Python3 to achieve the function of sending QQ mail: attachment, for your reference, the details are as follows

I can successfully send email attachments, but I can't send the main content of the email, so I'll look for the reason when I have time.

import smtplib
from  import MIMEText
from  import formataddr
from  import Header
my_sender = 'xxxx@' # Sender e-mail account
my_pass = 'xxxxx'    # Sender's e-mail password (the password given in the smtp application at the time)
my_user = 'xxxxxxx@'  # Recipient's e-mail account, sent to myself on my side r


def mail():
 ret = True
 try:
  msg = MIMEText(open('', 'rb').read(), 'base64', 'utf-8')
  msg["Content-Type"] = 'application/octet-stream'
  msg["Content-Disposition"] = 'attachment; filename=""'

  msg['From']=formataddr(["xxxxx", my_sender]) 
   # Corresponding to the sender's email nickname and sender's email account in parentheses.
  msg['To']=formataddr(["xxxxxx", my_user])    
   # Corresponding to the recipient's email nickname and recipient's email account in parentheses.
  msg['Subject']= 'Email Subject'   
   # The subject of the email, also known as the header

  server=smtplib.SMTP_SSL("", 465) 
   # SMTP server in the sender's mailbox on port 465
  (my_sender, my_pass) 
   # Corresponding to the sender's e-mail account and password in parentheses.
  (my_sender, [my_user,], msg.as_string()) 
   # The parentheses correspond to the sender's e-mail account, the recipient's e-mail account, and the sender's e-mail address.
  () # Close the connection
 except Exception: # If the statement in try is not executed, the following ret=False is executed
  ret = False
 return ret

ret = mail()
if ret:
 print("Mail sent successfully.")
else:
 print("Mail delivery failed.")

This is the entire content of this article.