import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from send_whatsapp2024 import generate_jeevnai_whatsapp_image from datetime import datetime def convert_date(date_str): # Parse the input string as a date formatted_date = date_str try: date_obj = datetime.strptime(date_str, '%Y%m%d') # Format the date in the desired output format formatted_date = date_obj.strftime('%d-%B-%Y') except: formatted_date = date_str return formatted_date def send_html_email( receiver_email, username, farm_name, farm_location, date_to_replace, image_url, payment_type, uid,fieldid, lang ): sender_email = "support@farmonaut.com" sender_password = "ankur@A8" html_file_path = "satellite_visit_template.html" image_url = "https://farmonaut.com/jeevn_ai_promo.jpg" print('payment_type', payment_type) if int(payment_type) == -2: image_url = generate_jeevnai_whatsapp_image('https://farmonaut.com/jeevn_ai_promo.jpg', uid, fieldid, lang, None) date_to_replace = convert_date(str(date_to_replace)) subject = f"Farmonaut's New Satellite Insights Could Change Your Harvest! See {farm_name} Farm's {date_to_replace} Report!" # Create a multipart message message = MIMEMultipart() message["From"] = sender_email message["To"] = receiver_email message["Subject"] = subject # Read the HTML file with open(html_file_path, "r", encoding="utf-8") as html_file: html_content = html_file.read() # Replace all the necessary data html_content = html_content.replace("USERNAME_TO_REPLACE", username) html_content = html_content.replace("FARMNAME_TO_REPLACE", farm_name) html_content = html_content.replace("FARMLOCATION_TO_REPLACE", farm_location) html_content = html_content.replace("DATE_TO_REPLACE", date_to_replace) html_content = html_content.replace("IMAGE_URL_TO_REPLACE", image_url) # Add HTML content to email message.attach(MIMEText(html_content, "html")) # Convert message to string text = message.as_string() # Log in to server using secure context and send email try: with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server: server.login(sender_email, sender_password) server.sendmail(sender_email, receiver_email, text) print("Email sent successfully!") except smtplib.SMTPAuthenticationError: print( "SMTP Authentication Error: The username and/or password you entered is incorrect." ) print( "Please check your credentials and make sure you're using an App Password if 2FA is enabled." ) except Exception as e: print(f"An error occurred: {e}")