Skip to content

Commit

Permalink
Merge pull request #372 from blondon1/patch-3
Browse files Browse the repository at this point in the history
Update code.py
  • Loading branch information
larymak authored Feb 2, 2024
2 parents 6d1e6e6 + 50b115d commit 9354d09
Showing 1 changed file with 42 additions and 34 deletions.
76 changes: 42 additions & 34 deletions AUTOMATION/Sending-Emails/code.py
Original file line number Diff line number Diff line change
@@ -1,36 +1,44 @@
###### Notice ######

# before sending email you have to enable your less secure apps access in your sending mail ([email protected])

import smtplib
import os
from email.message import EmailMessage

EMAIL_ADDRESS = "[email protected]" # your email-id goes here
EMAIL_PASSWORD = "xyz" # your password goes here

msg = EmailMessage()
msg['Subject'] = 'this is subject'
msg['From'] = EMAIL_ADDRESS
msg['To'] = EMAIL_ADDRESS

msg.set_content('Content area')

msg.add_alternative("""\
<html>
<body>
<h1>Your HTML CONTENT GOES HERE </h1>
</body>
</html>
""", subtype='html')

with open('testing.txt', 'rb') as f: # your filename will go here
file_data = f.read()
file_name = f.name

msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name)

with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)

smtp.send_message(msg)
print("Email Sent Successfully ..")
import logging

# Set up logging
logging.basicConfig(level=logging.INFO)

# Use environment variables for credentials
EMAIL_ADDRESS = os.getenv('EMAIL_ADDRESS')
EMAIL_PASSWORD = os.getenv('EMAIL_PASSWORD')

def send_email(subject, recipient, body, html_content=None, attachment_path=None):
msg = EmailMessage()
msg['Subject'] = subject
msg['From'] = EMAIL_ADDRESS
msg['To'] = recipient

msg.set_content(body)

if html_content:
msg.add_alternative(html_content, subtype='html')

if attachment_path:
try:
with open(attachment_path, 'rb') as f:
file_data = f.read()
file_name = f.name
msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name)
except FileNotFoundError:
logging.error(f"Attachment file {attachment_path} not found.")
return

try:
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
smtp.send_message(msg)
logging.info("Email Sent Successfully")
except Exception as e:
logging.error(f"An error occurred: {e}")

# Usage Example
send_email('Test Subject', '[email protected]', 'This is the email body',
'<html><body><h1>HTML Content</h1></body></html>', 'testing.txt')

0 comments on commit 9354d09

Please sign in to comment.