Skip to content

Create a Free Email Marketing Tool For WordPress Using Python

    Free Email Marketing Tool For WordPress

    Last Updated on: 31st October 2025, 03:41 pm

    This Email Marketing tool for WordPress is an amazing free tool for you to use. Just make some changes in Python Script and you are ready to go.

    Then You just need a TXT emails file to automate your blog posts just in one click.

    Complete Code for WordPress Email Marketing using Python

    import requests
    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email.mime.image import MIMEImage
    import urllib.request
    import os
    import logging
    
    # Set up logging
    logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
    
    def send_mail(post_title, post_url, post_excerpt, to_address):
        try:
            smtp_server = 'smtp.zoho.com'
            smtp_port = 465
            USERNAME = 'example@gmail.com'
            PASSWORD = '0Q1AXEXML1'
    
            from_address = USERNAME
    
            msg = MIMEMultipart('mixed')
            msg['Subject'] = "New Blog Post Alert!"
            msg['From'] = f"Deepdecide <{from_address}>"
            msg['To'] = to_address
    
            # Add error handling for image download
            try:
                img_data = urllib.request.urlopen('https://your-actual-image-url.jpg').read()
                image = MIMEImage(img_data, name=os.path.basename('banner.jpg'))
                image.add_header('Content-ID', '<banner>')
                msg.attach(image)
                has_image = True
            except Exception as e:
                logging.warning(f"Could not load image: {e}")
                has_image = False
    
            # Construct email in HTML format
            if has_image:
                html = f"""
                <html>
                    <body>
                        <h1>{post_title}</h1>
                        <p>{post_excerpt}</p>
                        <a href="{post_url}" target="_blank">
                            <img src="cid:banner" alt="{post_title}" style="max-width: 100%;" />
                        </a>
                        <p><a href="{post_url}">Read the full post</a></p>
                    </body>
                </html>
                """
            else:
                html = f"""
                <html>
                    <body>
                        <h1>{post_title}</h1>
                        <p>{post_excerpt}</p>
                        <p><a href="{post_url}">Read the full post</a></p>
                    </body>
                </html>
                """
    
            part = MIMEText(html, 'html')
            msg.attach(part)
    
            server = smtplib.SMTP_SSL(smtp_server, smtp_port)
            server.login(USERNAME, PASSWORD)
            server.sendmail(from_address, to_address, msg.as_string())
            server.quit()
            logging.info(f"Email sent successfully to {to_address}")
            
        except Exception as e:
            logging.error(f"Failed to send email to {to_address}: {e}")
    
    def send_new_post_alert():
        try:
            # Replace with your actual WordPress site URL
            wordpress_url = 'https://your-actual-wordpress-site.com/wp-json/wp/v2/posts'
            
            logging.info(f"Fetching posts from: {wordpress_url}")
            response = requests.get(wordpress_url, timeout=30)
            
            # Check if the request was successful
            response.raise_for_status()
            
            # Check if response content is not empty
            if not response.content:
                logging.error("Empty response from WordPress API")
                return
            
            posts = response.json()
            
            if not posts:
                logging.info("No posts found")
                return
    
            newest_post = posts[0]
            
            # Safely extract post data
            post_title = newest_post.get('title', {}).get('rendered', 'New Blog Post')
            post_url = newest_post.get('link', '#')
            post_excerpt = newest_post.get('excerpt', {}).get('rendered', 'Check out our latest blog post!')
    
            # Read email list with error handling
            try:
                with open('emails.txt', 'r') as f:
                    emails = [email.strip() for email in f.read().splitlines() if email.strip()]
            except FileNotFoundError:
                logging.error("emails.txt file not found")
                return
            except Exception as e:
                logging.error(f"Error reading emails file: {e}")
                return
    
            if not emails:
                logging.warning("No email addresses found in emails.txt")
                return
    
            logging.info(f"Found {len(emails)} email addresses to send to")
    
            for email in emails:
                send_mail(post_title, post_url, post_excerpt, email)
    
        except requests.exceptions.RequestException as e:
            logging.error(f"Network error fetching posts: {e}")
        except requests.exceptions.JSONDecodeError as e:
            logging.error(f"JSON decode error: {e}")
            logging.error(f"Response content: {response.text[:500]}")  # First 500 chars of response
        except Exception as e:
            logging.error(f"Unexpected error: {e}")
    
    if __name__ == "__main__":
        send_new_post_alert()

    Code Explanation

    Sure, let’s go through each part of the code:

    Modules Import:
    import requests
    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email.mime.image import MIMEImage
    import urllib

    requests: This library allows you to send HTTP requests easily, which you need to get the posts from your WordPress website.

    smtplib: This library is for sending emails using the Simple Mail Transfer Protocol (SMTP). We use it to send emails.

    email.mime.multipart.MIMEMultipart: This is a class to create MIME messages of major type multipart.

    email.mime.text.MIMEText: This is a class to create MIME text/* type messages.

    email.mime.image.MIMEImage: This class is used to create MIME message objects of major type image.

    urllib: This is a package that helps in opening URLs, which we use to get the image data.

    send_mail function:

    This is the function to send a single email. It sets up the SMTP server, composes the email message, and then sends it.

    First, SMTP server information (address, port), user login details (username and password), and email recipient details are defined.

    Then, we use the MIMEMultipart class to create an email message. The Subject, From, and To fields are then added.

    The function also organizes the message into a MIME friendly format, which is important for compatibility with a variety of email clients and servers. The email is then formatted with HTML, with a header section for the post title, a paragraph for the excerpt, and a link to the post URL with an attached image.

    send_new_post_alert function:

    This function is responsible for fetching the latest blog post from the website and sending the email alert. It accomplishes this by making a GET request to the WordPress REST API’s posts endpoint. The most recent post is then extracted, and the post title, URL, and excerpt are obtained. After these details are available, it reads the list of emails from emails.txt and calls the send_mail function for every email.

    Main Code:

    This is where the send_new_post_alert function is called if the script is run directly.

    if __name__ == "__main__":
        send_new_post_alert()

    You can run this script on your server, and it should automatically send an email for the newest post to every email address in the emails.txt file. You can also set up a scheduler (like a cron job, if you’re using a Unix-like operating system) to run this script at regular intervals, say daily or weekly, based on your requirements.

    As for how to achieve this part on the website, it can be managed via WordPress backend, using various plugins for sending automatic email updates to an email subscriber list e.g., MailPoet, Newsletter, etc. Or, a custom solution could be integrated with WordPress hooks for automatic email alerts.

    Please consult your progress with a web developer or administrator for website deployment practices and security liability.

    Share this post on social!

    Comment on Post

    Your email address will not be published. Required fields are marked *