Python Email Sending and Random String Generator

  • Share this:

Code introduction


This function defines an internal function to generate a random string and then defines a function to send an email. The email sending functionality uses Python's built-in libraries smtplib, email.mime.text.MIMEText, and email.mime.multipart.MIMEMultipart to construct and send emails.


Technology Stack : Python built-in libraries: random, string, os, sys, datetime, hashlib, json, re, socket, smtplib, email.mime.text, email.mime.multipart

Code Type : Function

Code Difficulty :


                
                    
import random
import string
import os
import sys
import datetime
import hashlib
import json
import re
import socket
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def generate_random_string(length=10):
    return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length))

def send_email(subject, body, to_email):
    sender_email = "your_email@example.com"
    sender_password = "your_password"

    message = MIMEMultipart()
    message["From"] = sender_email
    message["To"] = to_email
    message["Subject"] = subject

    message.attach(MIMEText(body, "plain"))

    server = smtplib.SMTP('smtp.example.com', 587)
    server.starttls()
    server.login(sender_email, sender_password)
    text = message.as_string()
    server.sendmail(sender_email, to_email, text)
    server.quit()