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 msg.SignPGP, msg.EncryptPGP,
216 )
217}
218
219func (p *Provider) FetchFolders(_ context.Context) ([]backend.Folder, error) {
220 return []backend.Folder{
221 {Name: "INBOX", Delimiter: "/"},
222 }, nil
223}
224
225func (p *Provider) Watch(_ context.Context, _ string) (<-chan backend.NotifyEvent, func(), error) {
226 return nil, nil, backend.ErrNotSupported
227}
228
229func (p *Provider) Close() error {
230 return nil
231}
232
233// Verify interface compliance at compile time.
234var _ backend.Provider = (*Provider)(nil)
235
236// findMessageByUID finds a POP3 message ID by matching the UID hash.
237func (p *Provider) findMessageByUID(conn *pop3client.Conn, uid uint32) (int, error) {
238 msgs, err := conn.Uidl(0)
239 if err != nil {
240 msgs, err = conn.List(0)
241 if err != nil {
242 return 0, fmt.Errorf("pop3 list: %w", err)
243 }
244 for _, m := range msgs {
245 if hashUID(fmt.Sprintf("%d", m.ID)) == uid {
246 return m.ID, nil
247 }
248 }
249 return 0, fmt.Errorf("pop3: message with UID %d not found", uid)
250 }
251
252 for _, m := range msgs {
253 if hashUID(m.UID) == uid {
254 return m.ID, nil
255 }
256 }
257 return 0, fmt.Errorf("pop3: message with UID %d not found", uid)
258}
259
260// hashUID converts a POP3 UIDL string to a uint32 hash.
261func hashUID(uidl string) uint32 {
262 var hash uint32
263 for _, c := range uidl {
264 hash = hash*31 + uint32(c)
265 }
266 if hash == 0 {
267 hash = 1
268 }
269 return hash
270}
271
272// entityToEmail converts message headers to a backend.Email.
273func entityToEmail(header *message.Header, msgInfo pop3client.MessageID, accountID string) backend.Email {
274 from := header.Get("From")
275 subject := header.Get("Subject")
276 dateStr := header.Get("Date")
277 messageID := header.Get("Message-ID")
278
279 var to []string
280 if toHeader := header.Get("To"); toHeader != "" {
281 for _, addr := range strings.Split(toHeader, ",") {
282 to = append(to, strings.TrimSpace(addr))
283 }
284 }
285
286 var date time.Time
287 if dateStr != "" {
288 if parsed, err := mail.ParseDate(dateStr); err == nil {
289 date = parsed
290 }
291 }
292
293 // Decode MIME-encoded headers
294 dec := new(mime.WordDecoder)
295 if decoded, err := dec.DecodeHeader(subject); err == nil {
296 subject = decoded
297 }
298 if decoded, err := dec.DecodeHeader(from); err == nil {
299 from = decoded
300 }
301
302 uidStr := msgInfo.UID
303 if uidStr == "" {
304 uidStr = fmt.Sprintf("%d", msgInfo.ID)
305 }
306
307 return backend.Email{
308 UID: hashUID(uidStr),
309 From: from,
310 To: to,
311 Subject: subject,
312 Date: date,
313 IsRead: false,
314 MessageID: messageID,
315 AccountID: accountID,
316 }
317}
318
319// parseMessageBody extracts the body text and attachments from a raw message.
320func parseMessageBody(r io.Reader) (string, []backend.Attachment, error) {
321 mr, err := gomail.CreateReader(r)
322 if err != nil {
323 // Not a multipart message — read body directly
324 body, err := io.ReadAll(r)
325 if err != nil {
326 return "", nil, err
327 }
328 return string(body), nil, nil
329 }
330
331 var bodyText string
332 var htmlBody string
333 var attachments []backend.Attachment
334 partIdx := 0
335
336 for {
337 part, err := mr.NextPart()
338 if err == io.EOF {
339 break
340 }
341 if err != nil {
342 break
343 }
344 partIdx++
345
346 contentType, _, _ := mime.ParseMediaType(part.Header.Get("Content-Type"))
347 disposition, dParams, _ := mime.ParseMediaType(part.Header.Get("Content-Disposition"))
348
349 data, readErr := io.ReadAll(part.Body)
350 if readErr != nil {
351 continue
352 }
353
354 if disposition == "attachment" || (disposition == "inline" && !strings.HasPrefix(contentType, "text/")) {
355 filename := dParams["filename"]
356 if filename == "" {
357 _, cp, _ := mime.ParseMediaType(part.Header.Get("Content-Type"))
358 filename = cp["name"]
359 }
360 att := backend.Attachment{
361 Filename: filename,
362 PartID: fmt.Sprintf("%d", partIdx),
363 Data: data,
364 MIMEType: contentType,
365 Inline: disposition == "inline",
366 }
367 if cid := part.Header.Get("Content-ID"); cid != "" {
368 att.ContentID = strings.Trim(cid, "<>")
369 }
370 attachments = append(attachments, att)
371 } else if contentType == "text/html" {
372 htmlBody = string(data)
373 } else if contentType == "text/plain" && bodyText == "" {
374 bodyText = string(data)
375 }
376 }
377
378 if htmlBody != "" {
379 return htmlBody, attachments, nil
380 }
381 return bodyText, attachments, nil
382}
383
384// findAttachmentData walks a raw message to find attachment data by partID.
385func findAttachmentData(r io.Reader, targetPartID string) ([]byte, error) {
386 mr, err := gomail.CreateReader(r)
387 if err != nil {
388 return nil, fmt.Errorf("not a multipart message")
389 }
390
391 partIdx := 0
392 for {
393 part, err := mr.NextPart()
394 if err == io.EOF {
395 break
396 }
397 if err != nil {
398 break
399 }
400 partIdx++
401
402 if fmt.Sprintf("%d", partIdx) == targetPartID {
403 return io.ReadAll(part.Body)
404 }
405 }
406
407 return nil, fmt.Errorf("pop3: attachment part %s not found", targetPartID)
408}