Class: MailMCP::SendMailMessageTool

Inherits:
Tool
  • Object
show all
Defined in:
lib/mail_mcp/tools/send_mail_message_tool.rb

Class Method Summary collapse

Methods inherited from Tool

format_from

Class Method Details

.call(to:, subject:, text_body:, server_context:, cc: nil, bcc: nil, html_body: nil, attachment_urls: [], folder: "Sent") ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/mail_mcp/tools/send_mail_message_tool.rb', line 30

def self.call(to:, subject:, text_body:, server_context:, cc: nil, bcc: nil, html_body: nil,
              attachment_urls: [], folder: "Sent")
  mail = MailBuilder.build(
    from: format_from(server_context),
    to: to, subject: subject, text_body: text_body,
    cc: cc, bcc: bcc, html_body: html_body,
    attachment_urls: attachment_urls
  )
  ImapClient.connect(server_context.imap_config) do |c|
    unless c.list_mailboxes.include?(folder)
      raise ImapClient::ConnectionError,
            "IMAP folder #{folder.inspect} does not exist. Use list_mailboxes to see available folders."
    end
  end

  SmtpClient.send(server_context.smtp_config, mail)

  begin
    ImapClient.connect(server_context.imap_config) do |c|
      c.append_message(folder: folder, raw_message: mail.to_s, flags: [:Seen])
    end
  rescue StandardError => e
    MailMCP.logger.warn { "Email sent but failed to save to IMAP folder=#{folder.inspect}: #{e.message}" }
    text = "Email sent successfully to #{to}, but could not be saved to #{folder}: #{e.message}"
    return MCP::Tool::Response.new([{ type: "text", text: text }])
  end

  MCP::Tool::Response.new([{ type: "text", text: "Email sent successfully to #{to} and saved to #{folder}" }])
end