forked from clementlecorre/mail-to-telegram
-
Notifications
You must be signed in to change notification settings - Fork 1
/
processing.go
98 lines (81 loc) · 1.75 KB
/
processing.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main
import (
"github.com/emersion/go-imap"
"gopkg.in/tucnak/telebot.v2"
"html"
"jaytaylor.com/html2text"
"log"
"strings"
"time"
)
func MailProcessing(msg []byte, mail *imap.Message) {
if mail == nil {
mail = &imap.Message{}
}
msgFmt := MessageFmt{
Subject: "",
Link: "N/A",
}
if mail.Envelope != nil {
msgFmt.Subject = mail.Envelope.Subject
}
msgFmt.Link = MailBodyProcessing(string(msg))
emailBody := MessageFormatting(msgFmt, mail)
arr := splitBodyByLimit(emailBody, 4000)
for _, tgBody := range arr {
tgBody = html.EscapeString(tgBody)
log.Println("Sending message to telegram, len=", len(tgBody))
_, err := b.Send(userID, tgBody, telebot.ModeHTML)
time.Sleep(time.Second)
if err != nil {
log.Fatal("telegram: ", err)
return
}
}
}
func splitBodyByLimit(text string, limit int) []string {
text = strings.TrimSpace(text)
if text == "" {
return nil
}
var res []string
current := ""
lines := strings.Split(text, "\n")
for _, line := range lines {
shortLines := splitLongLine(line, limit)
for _, short := range shortLines {
newCurrent := current + "\n" + line
if len(newCurrent) > limit {
res = append(res, current)
current = short
} else {
current = newCurrent
}
}
}
if current != "" {
res = append(res, current)
}
return res
}
func splitLongLine(line string, limit int) []string {
tmp := []rune(line)
var shortLines []string
for len(tmp) > 0 {
r := limit
if len(tmp) < r {
r = len(tmp)
}
shortLines = append(shortLines, string(tmp[:r]))
tmp = tmp[r:]
}
return shortLines
}
func MailBodyProcessing(msg string) string {
text, err := html2text.FromString(msg)
if err != nil {
log.Println("failed to do html2text: ", err)
return msg
}
return text
}