# **************************************************************************
#                                  _   _ ____  _
#  Project                     ___| | | |  _ \| |
#                             / __| | | | |_) | |
#                            | (__| |_| |  _ <| |___
#                             \___|\___/|_| \_\_____|
#
# Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
# SPDX-License-Identifier: curl
#
# **************************************************************************

"""
Send SMTP email using implicit TLS
"""

import sys
import ctypes as ct

import libcurl as lcurl
from curl_utils import *  # noqa

if not lcurl.CURL_AT_LEAST_VERSION(7, 20, 0):
    print("This example requires curl 7.20.0 or later", file=sys.stderr)
    sys.exit(-1)

# This is a simple example showing how to send mail using libcurl's SMTP
# capabilities. It builds on the smtp-mail.c example to add authentication
# and, more importantly, transport security to protect the authentication
# details from being snooped.

FROM_MAIL = "<sender@example.com>"
TO_MAIL   = "<recipient@example.com>"
CC_MAIL   = "<info@example.com>"

payload_text: str = (
    "Date: Mon, 29 Nov 2010 21:54:29 +1100\r\n"
    f"To: {TO_MAIL}\r\n"
    f"From: {FROM_MAIL}\r\n"
    f"Cc: {CC_MAIL}\r\n"
    "Message-ID: <dcd7cb36-11db-487a-9f3a-e652a9458efd@"
    "rfcpedant.example.org>\r\n"
    "Subject: SMTP example message\r\n"
    "\r\n"  # empty line to divide headers from body, see RFC 5322
    "The body of the message starts here.\r\n"
    "\r\n"
    "It could be a lot of lines, could be MIME encoded, whatever.\r\n"
    "Check RFC 5322.\r\n"
)

payload_data: bytes = payload_text.encode("utf-8")


class upload_status(ct.Structure):
    _fields_ = [
    ("bytes_read", ct.c_size_t),
]


@lcurl.read_callback
def payload_source(buffer, size, nitems, userp):
    upload_ctx = ct.cast(userp, ct.POINTER(upload_status)).contents
    buffer_size = nitems * size
    if buffer_size == 0: return 0
    data = payload_data[upload_ctx.bytes_read:]
    if not data: return 0
    nread = min(len(data), buffer_size)
    ct.memmove(buffer, data, nread)
    upload_ctx.bytes_read += nread
    return nread


def main(argv=sys.argv[1:]):

    url: str = argv[0] if len(argv) >= 1 else "smtp://mainserver.example.net:587"

    res: lcurl.CURLcode = lcurl.CURLE_OK
    upload_ctx = upload_status(0)

    curl: ct.POINTER(lcurl.CURL) = lcurl.easy_init()

    with curl_guard(False, curl) as guard:
        if not curl: return 1

        # Set username and password
        lcurl.easy_setopt(curl, lcurl.CURLOPT_USERNAME, b"user")
        lcurl.easy_setopt(curl, lcurl.CURLOPT_PASSWORD, b"secret")
        # This is the URL for your mailserver. Note the use of port 587 here,
        # instead of the normal SMTP port (25). Port 587 is commonly used for
        # secure mail submission (see RFC 4403), but you should use whatever
        # matches your server configuration.
        lcurl.easy_setopt(curl, lcurl.CURLOPT_URL, url.encode("utf-8"))
        # In this example, we start with a plain text connection, and upgrade to
        # Transport Layer Security (TLS) using the STARTTLS command. Be careful
        # of using CURLUSESSL_TRY here, because if TLS upgrade fails, the
        # transfer continues anyway - see the security discussion in the libcurl
        # libcurl tutorial for more details.
        lcurl.easy_setopt(curl, lcurl.CURLOPT_USE_SSL, lcurl.CURLUSESSL_ALL)
        # If your server does not have a valid certificate, then you can disable
        # part of the Transport Layer Security protection by setting the
        # CURLOPT_SSL_VERIFYPEER and CURLOPT_SSL_VERIFYHOST options to 0 (false).
        if defined("SKIP_PEER_VERIFICATION") and SKIP_PEER_VERIFICATION:
            lcurl.easy_setopt(curl, lcurl.CURLOPT_SSL_VERIFYPEER, 0)
        #   lcurl.easy_setopt(curl, lcurl.CURLOPT_SSL_VERIFYHOST, 0)
        # That is, in general, a bad idea. It is still better than sending your
        # authentication details in plain text though.  Instead, you should get
        # the issuer certificate (or the host certificate if the certificate is
        # self-signed) and add it to the set of certificates that are known to
        # libcurl using CURLOPT_CAINFO and/or CURLOPT_CAPATH. See docs/SSLCERTS
        # for more information.
        lcurl.easy_setopt(curl, lcurl.CURLOPT_CAINFO, b"/path/to/certificate.pem")
        # Note that this option is not strictly required, omitting it results in
        # libcurl sending the MAIL FROM command with empty sender data. All
        # autoresponses should have an empty reverse-path, and should be directed
        # to the address in the reverse-path which triggered them. Otherwise,
        # they could cause an endless loop. See RFC 5321 Section 4.5.5 for more
        # details.
        lcurl.easy_setopt(curl, lcurl.CURLOPT_MAIL_FROM, FROM_MAIL.encode("utf-8"))
        # Add two recipients, in this particular case they correspond to the
        # To: and Cc: addressees in the header, but they could be any kind of
        # recipient.
        recipients = ct.POINTER(lcurl.slist)()
        recipients = lcurl.slist_append(recipients, TO_MAIL.encode("utf-8"))
        recipients = lcurl.slist_append(recipients, CC_MAIL.encode("utf-8"))
        lcurl.easy_setopt(curl, lcurl.CURLOPT_MAIL_RCPT, recipients)
        # We are using a callback function to specify the payload (the headers and
        # body of the message). You could just use the CURLOPT_READDATA option to
        # specify a FILE pointer to read from.
        lcurl.easy_setopt(curl, lcurl.CURLOPT_READFUNCTION, payload_source)
        lcurl.easy_setopt(curl, lcurl.CURLOPT_READDATA, ct.byref(upload_ctx))
        lcurl.easy_setopt(curl, lcurl.CURLOPT_UPLOAD, 1)
        # Since the traffic is encrypted, it is useful to turn on debug
        # information within libcurl to see what is happening during the
        # transfer.
        lcurl.easy_setopt(curl, lcurl.CURLOPT_VERBOSE, 1)

        # Send the message
        res = lcurl.easy_perform(curl)

        # Check for errors
        handle_easy_perform_error(res)

        # Free the list of recipients
        lcurl.slist_free_all(recipients)

    return int(res)


sys.exit(main())
