1// Package pop3 implements the backend.Provider interface using POP3 for
2// reading email and SMTP for sending.
3//
4// POP3 is inherently limited compared to IMAP/JMAP:
5// - Only supports a single "INBOX" folder
6// - No support for flags (mark as read is a no-op)
7// - No support for moving or archiving emails
8// - No support for push notifications (IDLE)
9// - Delete marks for deletion; executed on Quit()
10package pop3
11
12import (
13 "context"
14 "fmt"
15 "io"
16 "mime"
17 "net/mail"
18 "strings"
19 "time"
20
21 "github.com/emersion/go-message"
22 gomail "github.com/emersion/go-message/mail"
23 pop3client "github.com/knadh/go-pop3"
24
25 "github.com/floatpane/matcha/backend"
26 "github.com/floatpane/matcha/config"
27 "github.com/floatpane/matcha/sender"
28)
29
30func init() {
31 backend.RegisterBackend("pop3", func(account *config.Account) (backend.Provider, error) {
32 return New(account)
33 })
34}
35
36// Provider implements backend.Provider using POP3+SMTP.
37type Provider struct {
38 account *config.Account
39 opt pop3client.Opt
40}
41
42// New creates a new POP3 provider for the given account.
43func New(account *config.Account) (*Provider, error) {
44 server := account.GetPOP3Server()
45 port := account.GetPOP3Port()
46
47 if server == "" {
48 return nil, fmt.Errorf("POP3 server not configured")
49 }
50
51 opt := pop3client.Opt{
52 Host: server,
53 Port: port,
54 TLSEnabled: true,
55 TLSSkipVerify: account.Insecure,
56 }
57
58 // Non-SSL ports use plain connection
59 if port == 110 {
60 opt.TLSEnabled = false
61 }
62
63 return &Provider{
64 account: account,
65 opt: opt,
66 }, nil
67}
68
69// connect creates a new POP3 connection and authenticates.
70func (p *Provider) connect() (*pop3client.Conn, error) {
71 client := pop3client.New(p.opt)
72 conn, err := client.NewConn()
73 if err != nil {
74 return nil, fmt.Errorf("pop3 connect: %w", err)
75 }
76
77 if err := conn.Auth(p.account.Email, p.account.Password); err != nil {
78 conn.Quit()
79 return nil, fmt.Errorf("pop3 auth: %w", err)
80 }
81
82 return conn, nil
83}
84
85func (p *Provider) FetchEmails(_ context.Context, _ string, limit, offset uint32) ([]backend.Email, error) {
86 conn, err := p.connect()
87 if err != nil {
88 return nil, err
89 }
90 defer conn.Quit()
91
92 // Get message list with UIDs
93 msgs, err := conn.Uidl(0)
94 if err != nil {
95 // Fallback to LIST if UIDL not supported
96 msgs, err = conn.List(0)
97 if err != nil {
98 return nil, fmt.Errorf("pop3 list: %w", err)
99 }
100 }
101
102 if len(msgs) == 0 {
103 return []backend.Email{}, nil
104 }
105
106 // POP3 messages are 1-indexed. We want newest first (highest ID first).
107 start := len(msgs) - int(offset)
108 if start <= 0 {
109 return []backend.Email{}, nil
110 }
111
112 end := start - int(limit)
113 if end < 0 {
114 end = 0
115 }
116
117 var emails []backend.Email
118 for i := start; i > end; i-- {
119 msgInfo := msgs[i-1]
120
121 // Fetch headers only using TOP (0 lines of body)
122 entity, err := conn.Top(msgInfo.ID, 0)
123 if err != nil {
124 continue
125 }
126
127 email := entityToEmail(&entity.Header, msgInfo, p.account.ID)
128 emails = append(emails, email)
129 }
130
131 return emails, nil
132}
133
134func (p *Provider) FetchEmailBody(_ context.Context, _ string, uid uint32) (string, []backend.Attachment, error) {
135 conn, err := p.connect()
136 if err != nil {
137 return "", nil, err
138 }
139 defer conn.Quit()
140
141 msgID, err := p.findMessageByUID(conn, uid)
142 if err != nil {
143 return "", nil, err
144 }
145
146 raw, err := conn.RetrRaw(msgID)
147 if err != nil {
148 return "", nil, fmt.Errorf("pop3 retr: %w", err)
149 }
150
151 return parseMessageBody(raw)
152}
153
154func (p *Provider) FetchAttachment(_ context.Context, _ string, uid uint32, partID, _ string) ([]byte, error) {
155 conn, err := p.connect()
156 if err != nil {
157 return nil, err
158 }
159 defer conn.Quit()
160
161 msgID, err := p.findMessageByUID(conn, uid)
162 if err != nil {
163 return nil, err
164 }
165
166 raw, err := conn.RetrRaw(msgID)
167 if err != nil {
168 return nil, fmt.Errorf("pop3 retr: %w", err)
169 }
170
171 return findAttachmentData(raw, partID)
172}
173
174func (p *Provider) MarkAsRead(_ context.Context, _ string, _ uint32) error {
175 // POP3 has no concept of read/unread flags — this is a no-op
176 return nil
177}
178
179func (p *Provider) DeleteEmail(_ context.Context, _ string, uid uint32) error {
180 conn, err := p.connect()
181 if err != nil {
182 return err
183 }
184
185 msgID, err := p.findMessageByUID(conn, uid)
186 if err != nil {
187 conn.Quit()
188 return err
189 }
190
191 if err := conn.Dele(msgID); err != nil {
192 conn.Quit()
193 return fmt.Errorf("pop3 dele: %w", err)
194 }
195
196 // Quit commits the deletion
197 return conn.Quit()
198}
199
200func (p *Provider) ArchiveEmail(_ context.Context, _ string, _ uint32) error {
201 return backend.ErrNotSupported
202}
203
204func (p *Provider) MoveEmail(_ context.Context, _ uint32, _, _ string) error {
205 return backend.ErrNotSupported
206}
207
208func (p *Provider) SendEmail(_ context.Context, msg *backend.OutgoingEmail) error {
209 return sender.SendEmail(
210 p.account, msg.To, msg.Cc, msg.Bcc,
211 msg.Subject, msg.PlainBody, msg.HTMLBody,
212 msg.Images, msg.Attachments,
213 msg.InReplyTo, msg.References,
214 msg.SignSMIME, msg.EncryptSMIME,
215 )
216}
217
218func (p *Provider) FetchFolders(_ context.Context) ([]backend.Folder, error) {
219 return []backend.Folder{
220 {Name: "INBOX", Delimiter: "/"},
221 }, nil
222}
223
224func (p *Provider) Watch(_ context.Context, _ string) (<-chan backend.NotifyEvent, func(), error) {
225 return nil, nil, backend.ErrNotSupported
226}
227
228func (p *Provider) Close() error {
229 return nil
230}
231
232// Verify interface compliance at compile time.
233var _ backend.Provider = (*Provider)(nil)
234
235// findMessageByUID finds a POP3 message ID by matching the UID hash.
236func (p *Provider) findMessageByUID(conn *pop3client.Conn, uid uint32) (int, error) {
237 msgs, err := conn.Uidl(0)
238 if err != nil {
239 msgs, err = conn.List(0)
240 if err != nil {
241 return 0, fmt.Errorf("pop3 list: %w", err)
242 }
243 for _, m := range msgs {
244 if hashUID(fmt.Sprintf("%d", m.ID)) == uid {
245 return m.ID, nil
246 }
247 }
248 return 0, fmt.Errorf("pop3: message with UID %d not found", uid)
249 }
250
251 for _, m := range msgs {
252 if hashUID(m.UID) == uid {
253 return m.ID, nil
254 }
255 }
256 return 0, fmt.Errorf("pop3: message with UID %d not found", uid)
257}
258
259// hashUID converts a POP3 UIDL string to a uint32 hash.
260func hashUID(uidl string) uint32 {
261 var hash uint32
262 for _, c := range uidl {
263 hash = hash*31 + uint32(c)
264 }
265 if hash == 0 {
266 hash = 1
267 }
268 return hash
269}
270
271// entityToEmail converts message headers to a backend.Email.
272func entityToEmail(header *message.Header, msgInfo pop3client.MessageID, accountID string) backend.Email {
273 from := header.Get("From")
274 subject := header.Get("Subject")
275 dateStr := header.Get("Date")
276 messageID := header.Get("Message-ID")
277
278 var to []string
279 if toHeader := header.Get("To"); toHeader != "" {
280 for _, addr := range strings.Split(toHeader, ",") {
281 to = append(to, strings.TrimSpace(addr))
282 }
283 }
284
285 var date time.Time
286 if dateStr != "" {
287 if parsed, err := mail.ParseDate(dateStr); err == nil {
288 date = parsed
289 }
290 }
291
292 // Decode MIME-encoded headers
293 dec := new(mime.WordDecoder)
294 if decoded, err := dec.DecodeHeader(subject); err == nil {
295 subject = decoded
296 }
297 if decoded, err := dec.DecodeHeader(from); err == nil {
298 from = decoded
299 }
300
301 uidStr := msgInfo.UID
302 if uidStr == "" {
303 uidStr = fmt.Sprintf("%d", msgInfo.ID)
304 }
305
306 return backend.Email{
307 UID: hashUID(uidStr),
308 From: from,
309 To: to,
310 Subject: subject,
311 Date: date,
312 IsRead: false,
313 MessageID: messageID,
314 AccountID: accountID,
315 }
316}
317
318// parseMessageBody extracts the body text and attachments from a raw message.
319func parseMessageBody(r io.Reader) (string, []backend.Attachment, error) {
320 mr, err := gomail.CreateReader(r)
321 if err != nil {
322 // Not a multipart message — read body directly
323 body, err := io.ReadAll(r)
324 if err != nil {
325 return "", nil, err
326 }
327 return string(body), nil, nil
328 }
329
330 var bodyText string
331 var htmlBody string
332 var attachments []backend.Attachment
333 partIdx := 0
334
335 for {
336 part, err := mr.NextPart()
337 if err == io.EOF {
338 break
339 }
340 if err != nil {
341 break
342 }
343 partIdx++
344
345 contentType, _, _ := mime.ParseMediaType(part.Header.Get("Content-Type"))
346 disposition, dParams, _ := mime.ParseMediaType(part.Header.Get("Content-Disposition"))
347
348 data, readErr := io.ReadAll(part.Body)
349 if readErr != nil {
350 continue
351 }
352
353 if disposition == "attachment" || (disposition == "inline" && !strings.HasPrefix(contentType, "text/")) {
354 filename := dParams["filename"]
355 if filename == "" {
356 _, cp, _ := mime.ParseMediaType(part.Header.Get("Content-Type"))
357 filename = cp["name"]
358 }
359 att := backend.Attachment{
360 Filename: filename,
361 PartID: fmt.Sprintf("%d", partIdx),
362 Data: data,
363 MIMEType: contentType,
364 Inline: disposition == "inline",
365 }
366 if cid := part.Header.Get("Content-ID"); cid != "" {
367 att.ContentID = strings.Trim(cid, "<>")
368 }
369 attachments = append(attachments, att)
370 } else if contentType == "text/html" {
371 htmlBody = string(data)
372 } else if contentType == "text/plain" && bodyText == "" {
373 bodyText = string(data)
374 }
375 }
376
377 if htmlBody != "" {
378 return htmlBody, attachments, nil
379 }
380 return bodyText, attachments, nil
381}
382
383// findAttachmentData walks a raw message to find attachment data by partID.
384func findAttachmentData(r io.Reader, targetPartID string) ([]byte, error) {
385 mr, err := gomail.CreateReader(r)
386 if err != nil {
387 return nil, fmt.Errorf("not a multipart message")
388 }
389
390 partIdx := 0
391 for {
392 part, err := mr.NextPart()
393 if err == io.EOF {
394 break
395 }
396 if err != nil {
397 break
398 }
399 partIdx++
400
401 if fmt.Sprintf("%d", partIdx) == targetPartID {
402 return io.ReadAll(part.Body)
403 }
404 }
405
406 return nil, fmt.Errorf("pop3: attachment part %s not found", targetPartID)
407}