如何使用Brevo API在Django基于函数的视图中发送电子邮件

eblbsuwk  于 2023-11-20  发布在  Go
关注(0)|答案(1)|浏览(149)

我已经开发了一个Django Web应用程序,并集成了使用Brevo(正式名称为SendinBlue)发送自定义电子邮件。
我的settings.py发送电子邮件的文件配置良好,因为我能够接收密码重置电子邮件,但我无法在基于功能的视图中发送电子邮件.我想在应用程序批准后发送电子邮件给用户,但我得到了
“User”对象没有属性“swagger_types”
请参阅下面我的视图代码,其中集成了用于发送电子邮件的API:

from __future__ import print_function
import sib_api_v3_sdk
from sib_api_v3_sdk.rest import ApiException

@login_required(login_url='user-login')
def approve_applicant(request, pk):
    # Get Applicant id 
    app_id = Profile.objects.get(id=pk)
    # Get Applicant's names
    app_user = app_id.applicant
    applicant_detail = app_id.surname
    app_othername = app_id.othernames
    app_phone = app_id.phone
    app_email = app_id.applicant.email
    # app_edu = app_id.applicant.education.qualification
    # Try Check Application Submission
    try:
        app_id = Submitted.objects.get(applicant=app_user) 
    # When Applicant is Not Found
    except Submitted.DoesNotExist:
        # Send Message
        messages.error(request, f"{applicant_detail} {app_othername}  has No Submited Application")
        # Redirect Back
        return redirect('search-applicant')
    else:
        approved = Fee.objects.count()
        if request.method == "POST":
            # applicant = Submitted.objects.get(applicant_id=pk) 
            # Filter and Update scholarship Approval
            Submitted.objects.filter(applicant_id=pk).update(approved='APROVED')
            record_fee=Fee.objects.create(applicant=app_user, email=app_email, phone=app_phone)
            record_fee.save()
            # Instantiate the client with the API KEY
            configuration = sib_api_v3_sdk.Configuration()
            configuration.api_key['api-key']=config('API_KEY')
            api_instance = sib_api_v3_sdk.TransactionalEmailsApi(sib_api_v3_sdk.ApiClient(configuration))
            # Define the campaign settings\
            subject = "SUCCESSGANDE SCHOLARSHIP PORTAL!"
            sender = {"name": "SUCCESSGANDE", "email": "[email protected]"}
            replyTo = {"name": "SUCCESSGANDE", "email": "[email protected]"}
            html_content = "<html><body><h1>Congratulations! Your Scholarship Application has been approved. </h1></body></html>"
            to = [{"email": app_email, "name": app_user}]
            params = {"parameter": "My param value", "subject": "New Subject"}
            send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(to=to, bcc='[email protected]', cc='[email protected]', reply_to=replyTo, headers='Testing', html_content=html_content, sender=sender, subject=subject)

            try:
                api_response = api_instance.send_transac_email(send_smtp_email)
                print(api_response)
            except ApiException as e:
                print("Exception when calling SMTPApi->send_transac_email: %s\n" % e)
                print("Exception when calling EmailCampaignsApi->create_email_campaign: %s\n" % e)
            messages.success(request, f'{applicant_detail} {app_othername} Scholarship Approved successfully')
            return redirect('search-applicant') 
        context = {
            'applicant': applicant_detail,
            'app_othername': app_othername,
            'app_user': app_user,
            'approved': approved,
        }
        return render(request, 'user/approval_form.html', context)

字符串
有人应该善意地分享我如何最好地实现在我看来使用BREVO(SendinBlue)API在Django基于函数的视图中发送电子邮件。

qni6mghb

qni6mghb1#

您遇到的错误,'User'对象没有属性'swagger_types',似乎与Brevo(SendinBlue)库在User对象中期望某些属性有关,这不是Django的User模型的一部分。
在你的例子中,看起来你试图传递app_user(这是一个User对象)作为电子邮件的收件人。Brevo库可能需要User对象上的其他属性或方法,而这些属性或方法在Django User模型中没有。
要解决此问题,您可以尝试以下操作:
1.**直接传递Email和Name:**不要将整个app_user对象传递到to字段,而是提取Email和Name并直接传递:

to = [{"email": app_email, "name": f"{app_user.first_name} {app_user.last_name}"}]

字符串
确保app_user具有first_namelast_name属性。如果没有,您可能需要根据您的用户模型调整此属性。
1.**将电子邮件作为字符串传递:**某些库要求电子邮件地址作为字符串传递,因此您也可以尝试将电子邮件直接作为字符串传递:

to = app_email


这将取决于Brevo图书馆的要求。
1.**查看文档:**参考Brevo(SendinBlue)库的文档,查看to字段中收件人信息的预期格式。
如果库需要特定的属性,您可能需要调整用户模型或创建自定义DTO(数据传输对象)来满足这些要求。
下面是一个包含第一个建议的示例:

# Extract user details
to_name = f"{app_user.first_name} {app_user.last_name}"
to_email = app_email

# Define recipient
to = [{"email": to_email, "name": to_name}]


确保根据用户模型的实际属性和Brevo库的要求调整代码。

相关问题