Files
2024-09-22 20:02:30 +02:00

87 lines
3.0 KiB
Python

from __future__ import unicode_literals
from django.db import models
import os
from modelcluster.fields import ParentalKey
from wagtail.models import Page
from wagtail.contrib.forms.models import AbstractEmailForm, AbstractFormField
from wagtail.fields import RichTextField
from wagtail.admin.panels import FieldPanel, FieldRowPanel,InlinePanel, MultiFieldPanel
from saburly.custom_editor import FULL_EDITOR
import sib_api_v3_sdk
from sib_api_v3_sdk.rest import ApiException
from dotenv import load_dotenv
load_dotenv()
class FormField(AbstractFormField):
page = ParentalKey(
'ContactPage',
on_delete = models.CASCADE,
related_name= 'form_fields'
)
class ContactPage(AbstractEmailForm):
section_one_title = RichTextField(blank=True, features=FULL_EDITOR)
section_one_text = RichTextField(blank=True, features=FULL_EDITOR)
section_one_img = RichTextField(blank=True, features=FULL_EDITOR)
section_two_title = RichTextField(blank=True, features=FULL_EDITOR)
section_two_text = RichTextField(blank=True, features=FULL_EDITOR)
section_two_img = RichTextField(blank=True, features=FULL_EDITOR)
content_panels = AbstractEmailForm.content_panels + [
MultiFieldPanel([
FieldPanel('section_one_title', classname="full"),
FieldPanel('section_one_text', classname="full"),
FieldPanel('section_one_img', classname="full"),
], heading="Section One"),
MultiFieldPanel([
FieldPanel('section_two_title', classname="full"),
FieldPanel('section_two_text', classname="full"),
FieldPanel('section_two_img', classname="full"),
], heading="Section Two"),
InlinePanel('form_fields',label='Form Fields'),
MultiFieldPanel([
FieldRowPanel([
FieldPanel('from_address', classname='saburly-input'),
FieldPanel('to_address', classname='saburly-input'),
]),
FieldPanel('subject'),
], heading = 'Email Settings'),
]
def send_mail(self, form):
form_data = '\n'.join([f"{field.label}: {form.cleaned_data.get(field.name)}" for field in form])
configuration = sib_api_v3_sdk.Configuration()
configuration.api_key['api-key'] = os.getenv('EMAIL_API')
api_instance = sib_api_v3_sdk.TransactionalEmailsApi(sib_api_v3_sdk.ApiClient(configuration))
subject = self.subject or "New Contact Form Submission"
sender = {"email": self.from_address}
to = [{"email": self.to_address}]
html_content = f"<html><body><pre>{form_data}</pre></body></html>"
send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(
to=to,
sender=sender,
subject=subject,
html_content=html_content
)
try:
api_instance.send_transac_email(send_smtp_email)
print("Email sent successfully")
except ApiException as e:
print(f"Failed to send email: {e}")