- import smtplib
- from email.mime.text import MIMEText
- from email.mime.multipart import MIMEMultipart
- def send_email(sender_email, sender_password, receiver_email, subject, body):
- try:
- # SMTP server configuration
- smtp_server = 'xxx.net'
- smtp_port = 465
- # Create a secure connection to the server
- server = smtplib.SMTP(smtp_server, smtp_port)
- server.starttls()
- # Log in to the server
- server.login(sender_email, sender_password)
- # Create a message
- message = MIMEMultipart()
- message['From'] = 'xxx@ xxxx.net'
- message['To'] = 'xxx@ xxxx.net'
- message['Subject'] = subject
- # Add body to the message
- message.attach(MIMEText(body, 'plain'))
- # Send the email
- server.sendmail(sender_email, receiver_email, message.as_string())
- # Close the connection
- server.quit()
- print("Email sent successfully!")
- except Exception as e:
- print(f"An error occurred: {e}")
- # Usage example
- if __name__ == "__main__":
- sender_email = 'xxx@ xxxx.net'
- sender_password = '' # Replace with the actual password
- receiver_email = xxx@ xxxx.net'
- subject = 'Test Email'
- body = 'This is a test email sent using Python SMTP.'
- send_email(sender_email, sender_password, receiver_email, subject, body)
复制代码 这是我的python代码,发送邮件没有问题,公网和内网均可以 |