import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
class EmailSender:
def __init__(self, smtp_server, port, sender_email, password):
self.smtp_server = smtp_server
self.port = port
self.sender_email = sender_email
self.password = password
def send_email(self, receiver_email, subject, body, attachment_path=None):
message = MIMEMultipart()
message['From'] = self.sender_email
message['To'] = receiver_email
message['Subject'] = subject
message.attach(MIMEText(body, 'plain'))
if attachment_path:
attachment = open(attachment_path, "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', f"attachment; filename= {attachment_path}")
message.attach(part)
with smtplib.SMTP_SSL(self.smtp_server, self.port) as server:
server.login(self.sender_email, self.password)
server.sendmail(self.sender_email, receiver_email, message.as_string())
# Example usage:
if __name__ == "__main__":
smtp_server = 'smtp.example.com'
port = 465 # SSL port
sender_email = 'your_email@example.com'
password = 'your_password'
receiver_email = 'recipient@example.com'
subject = 'Automated Email with Attachment'
body = 'This email is sent automatically using Python.'
attachment_path = 'path/to/attachment.txt'
email_sender = EmailSender(smtp_server, port, sender_email, password)
email_sender.send_email(receiver_email, subject, body, attachment_path)