0

I am a newbie Python developer. I am using Google's InstalledAppFlow to send emails to addresses listed in an input.txt file. The code works fine on my local PC, and I am able to receive emails on Outlook. However, when I run the code on a VPS, there are no errors, but the emails are not delivered to Outlook.

Here is the code snippet I am using for sending emails:

def send_mail(sender_name, sender_email, receiver, subject, message_content, cc_email, html, file_path):
    try:

        service = build('gmail', 'v1', credentials=creds)

        primary_alias = None
        send_as_configuration = {
            'displayName': sender_name,
        }
        aliases = service.users().settings().sendAs().list(userId='me') \
            .execute()
        for alias in aliases.get('sendAs'):
            if alias.get('isPrimary'):
                primary_alias = alias
                break
        result = service.users().settings().sendAs() \
            .patch(userId='me', sendAsEmail=primary_alias.get('sendAsEmail'),
                   body=send_as_configuration).execute()

        message = MIMEMultipart()
        if html:
            part1 = MIMEText(message_content, "html")
        else:
            part1 = MIMEText(message_content, "plain")
        message.attach(part1)

        with open(file_path, "rb") as f:
            part2 = MIMEApplication(
                f.read(),
                Name=os.path.basename(file_path)
            )
            part2['Content-Disposition'] = f'attachment; filename= {os.path.basename(file_path)}'
            message.attach(part2)

        message['From'] = sender_email
        message['CC'] = cc_email
        print(receiver)
        message['To'] = receiver
        message['Subject'] = subject

        encoded_message = base64.urlsafe_b64encode(message.as_bytes()).decode()

        create_message = {
            'raw': encoded_message
        }
        send_message = (service.users().messages().send
                        (userId="me", body=create_message).execute())
        print(F'Message Id: {send_message["id"]}')

    except HttpError as error:
        print(F'An error occurred: {error}')


def invoice_pdf(company, add, name):

    packet = io.BytesIO()
    can = canvas.Canvas(packet, pagesize=letter)
    can.drawString(37, 570, company)
    can.drawString(37, 550, add)
    can.drawString(37, 530, " Attn: " + name)
    can.save()

    # move to the beginning of the StringIO buffer
    packet.seek(0)

    # create a new PDF with Reportlab
    new_pdf = PdfReader(packet)
    # read your existing PDF
    existing_pdf = PdfReader(open("sample.pdf", "rb"))
    output = PdfWriter()
    # add the "watermark" (which is the new pdf) on the existing page
    page = existing_pdf.pages[0]
    page.merge_page(new_pdf.pages[0])
    output.add_page(page)
    # finally, write "output" to a real file
    output_stream = open("invoice.pdf", "wb")
    output.write(output_stream)
    output_stream.close()

I have also added SMTP rules in the outbound firewall options, but I am still unable to fix the issue. Any help or suggestions would be greatly appreciated.

Robert
  • 7,394
  • 40
  • 45
  • 64
  • 1
    A [mcve] would be helpful. What happens to the emails in production? Do they bounce? (This may take a few days, depending on the mail server settings.) Do they end up in the spam folder? Can you simplify your emails, e.g., send without attachments? – Robert Jul 05 '23 at 18:31
  • 1
    If mail disappears instead of bouncing or ending up in a spam or junk folder, you can try sending to a mail server with looser checks, like a personal domain. Look at the incoming headers to see if SPF, DKIM validation succeeded. – Dave S Jul 05 '23 at 18:35
  • 1
    Also check server and google logs -- it might be something like the VPS port is blocked so it can't connect to send, or you might not have set up something else correctly. – Dave S Jul 05 '23 at 18:37

0 Answers0