|
| 1 | +import os |
| 2 | +import smtplib |
| 3 | +from email.mime.text import MIMEText |
| 4 | +from email.mime.multipart import MIMEMultipart |
| 5 | + |
| 6 | +def send_email(sender_email, recipient_email, subject, message): |
| 7 | + # SMTP server configuration |
| 8 | + smtp_server = 'smtp.gmail.com' |
| 9 | + smtp_port = 587 |
| 10 | + |
| 11 | + # Get the sender password from an environment variable |
| 12 | + sender_password = os.environ.get('EMAIL_PASSWORD') |
| 13 | + |
| 14 | + if not sender_password: |
| 15 | + print("Error: Email password not set in environment variable.") |
| 16 | + return |
| 17 | + |
| 18 | + # Create the email message |
| 19 | + email = MIMEMultipart() |
| 20 | + email['From'] = sender_email |
| 21 | + email['To'] = recipient_email |
| 22 | + email['Subject'] = subject |
| 23 | + |
| 24 | + # Create a MIMEText object with HTML content |
| 25 | + html_content = ''' |
| 26 | + <html> |
| 27 | + <body> |
| 28 | + <h1>{}</h1> |
| 29 | + <p>{}</p> |
| 30 | + <p>This is a <strong>bold</strong> example.</p> |
| 31 | + <p>This is an <em>italic</em> example.</p> |
| 32 | + </body> |
| 33 | + </html> |
| 34 | + '''.format(subject, message) |
| 35 | + |
| 36 | + email.attach(MIMEText(html_content, 'html')) |
| 37 | + |
| 38 | + # Connect to the SMTP server |
| 39 | + server = smtplib.SMTP(smtp_server, smtp_port) |
| 40 | + server.starttls() |
| 41 | + server.login(sender_email, sender_password) |
| 42 | + |
| 43 | + # Send the email |
| 44 | + server.sendmail(sender_email, recipient_email, email.as_string()) |
| 45 | + |
| 46 | + # Close the connection |
| 47 | + server.quit() |
| 48 | + |
| 49 | +# Example usage |
| 50 | +sender_email = '[email protected]' |
| 51 | +recipient_email = '[email protected]' |
| 52 | +subject = 'Hello from Python Email Script' |
| 53 | +message = 'This is an automated email sent using Python.' |
| 54 | + |
| 55 | +send_email(sender_email, recipient_email, subject, message) |
0 commit comments