1 import {
2 Logger,
3 NotificationTypes,
4 SendgridNotificationServiceOptions,
5 } from "@medusajs/framework/types"
6 import {
7 AbstractNotificationProviderService,
8 MedusaError,
9 } from "@medusajs/framework/utils"
10 import sendgrid from "@sendgrid/mail"
11
12 type InjectedDependencies = {
13 logger: Logger
14 }
15
16 type MailContent = Required<Omit<NotificationTypes.NotificationContent, "text">>
17
18 interface SendgridServiceConfig {
19 apiKey: string
20 from: string
21 }
22
23 export class SendgridNotificationService extends AbstractNotificationProviderService {
24 static identifier = "notification-sendgrid"
25 protected config_: SendgridServiceConfig
26 protected logger_: Logger
27
28 constructor(
29 { logger }: InjectedDependencies,
30 options: SendgridNotificationServiceOptions
31 ) {
32 super()
33
34 this.config_ = {
35 apiKey: options.api_key,
36 from: options.from,
37 }
38 this.logger_ = logger
39 sendgrid.setApiKey(this.config_.apiKey)
40 }
41
42 async send(
43 notification: NotificationTypes.ProviderSendNotificationDTO
44 ): Promise<NotificationTypes.ProviderSendNotificationResultsDTO> {
45 if (!notification) {
46 throw new MedusaError(
47 MedusaError.Types.INVALID_DATA,
48 `No notification information provided`
49 )
50 }
51
52 const attachments = Array.isArray(notification.attachments)
53 ? notification.attachments.map((attachment) => ({
54 content: attachment.content, // Base64 encoded string of the file
55 filename: attachment.filename,
56 content_type: attachment.content_type, // MIME type (e.g., 'application/pdf')
57 disposition: attachment.disposition ?? "attachment", // Default to 'attachment'
58 id: attachment.id ?? undefined, // Optional: unique identifier for inline attachments
59 }))
60 : undefined
61
62 const from = notification.from?.trim() || this.config_.from
63
64 let mailContent:
65 | MailContent
66 | {
67 templateId: string
68 }
69
70 if ("content" in notification && !!notification.content) {
71 mailContent = {
72 subject: notification.content?.subject,
73 html: notification.content?.html,
74 } as MailContent
75 } else {
76 // we can't mix html and templates for sendgrid
77 mailContent = {
78 templateId: notification.template,
79 }
80 }
81
82 const personalizations = notification.provider_data?.personalizations as
83 | sendgrid.MailDataRequired["personalizations"]
84 | undefined
85
86 const message: sendgrid.MailDataRequired = {
87 from: from,
88 dynamicTemplateData: notification.data as
89 | { [key: string]: any }
90 | undefined,
91 attachments: attachments,
92 ...(personalizations?.length ? { personalizations } : { to: notification.to }),
93 ...mailContent,
94 }
95
96 try {
97 // Unfortunately we don't get anything useful back in the response
98 await sendgrid.send(message)
99 return {}
100 } catch (error) {
101 const errorCode = error.code
102 const responseError = error.response?.body?.errors?.[0]
103 throw new MedusaError(
104 MedusaError.Types.UNEXPECTED_STATE,
105 `Failed to send email: ${errorCode} - ${
106 responseError?.message ?? "unknown error"
107 }`
108 )
109 }
110 }
111 }