-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKindleEmailSender.java
More file actions
251 lines (224 loc) · 10.5 KB
/
Copy pathKindleEmailSender.java
File metadata and controls
251 lines (224 loc) · 10.5 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import jakarta.mail.Authenticator;
import jakarta.mail.Message;
import jakarta.mail.MessagingException;
import jakarta.mail.PasswordAuthentication;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeBodyPart;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.internet.MimeMultipart;
/**
* Sends a generated ebook as an email attachment to configured recipient addresses.
* Uses Jakarta Mail with Gmail SMTP so MIME formatting is standards-compliant.
*
* This class used to build raw MIME messages by hand. That was good enough for
* normal inboxes but brittle for Kindle ingestion, so we now delegate message
* construction to Jakarta Mail and keep our own logic focused on configuration.
*/
public class KindleEmailSender {
private static final String SMTP_HOST = "smtp.gmail.com";
private static final int SMTP_PORT = 465;
public static boolean isConfigured() {
return validateConfiguration(false);
}
public static boolean printPreflightCheck() {
return validateConfiguration(true);
}
public static void sendToKindle(Path ebookPath) {
// Preflight checks are intentionally shared with the CLI so the user gets a
// clear configuration message before conversion work starts.
if (!validateConfiguration(true)) {
return;
}
String senderEmail = ReadstackConfig.get("READSTACK_SMTP_EMAIL");
String senderPassword = getSmtpPassword();
List<String> recipientEmails = getRecipientEmails();
if (ebookPath == null || !Files.isRegularFile(ebookPath)) {
System.out.println("Kindle delivery skipped: ebook file not found.");
return;
}
System.out.println("Sending EPUB to recipients...");
try {
// We send separately to each recipient instead of using one multi-recipient
// message because Kindle and regular inboxes can behave differently, and
// per-recipient sends make delivery failures easier to reason about.
for (String recipientEmail : recipientEmails) {
sendMessage(senderEmail, senderPassword, recipientEmail, ebookPath);
}
System.out.println("EPUB delivery complete.");
} catch (Exception e) {
System.out.println("EPUB delivery failed: " + e.getMessage());
}
}
private static void sendMessage(String senderEmail, String senderPassword, String recipientEmail, Path ebookPath)
throws MessagingException, IOException {
Properties props = new Properties();
// Gmail on port 465 expects implicit SSL. We keep the config explicit here so
// the behavior is readable without digging through Jakarta Mail defaults.
props.put("mail.smtp.host", SMTP_HOST);
props.put("mail.smtp.port", Integer.toString(SMTP_PORT));
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.protocols", "TLSv1.2 TLSv1.3");
// Jakarta Mail builds a standards-compliant message with proper headers,
// boundaries, and encodings. That is the main reason this path is more robust
// than the earlier hand-built SMTP implementation.
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(senderEmail, senderPassword);
}
});
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(senderEmail));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false));
message.setSubject("Readstack delivery", StandardCharsets.UTF_8.name());
// The plain-text body is intentionally tiny. The attachment is the product,
// and extra body formatting does not help Kindle delivery.
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText("Sent by Readstack.", StandardCharsets.UTF_8.name());
// We force the EPUB content type so downstream mail handling and Kindle both
// see the attachment as an ebook instead of generic binary data.
MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.attachFile(ebookPath.toFile());
attachmentPart.setHeader("Content-Type", "application/epub+zip; name=\"" + ebookPath.getFileName() + "\"");
attachmentPart.setFileName(ebookPath.getFileName().toString());
MimeMultipart multipart = new MimeMultipart();
multipart.addBodyPart(textPart);
multipart.addBodyPart(attachmentPart);
message.setContent(multipart);
message.saveChanges();
Transport.send(message);
}
private static boolean validateConfiguration(boolean verbose) {
// Configuration validation is centralized here so the CLI and delivery code do
// not drift apart when new config keys or fallback paths are added later.
String senderEmail = ReadstackConfig.get("READSTACK_SMTP_EMAIL");
String senderPassword = getSmtpPassword();
List<String> recipientEmails = getRecipientEmails();
String keychainService = getKeychainService();
boolean valid = true;
if (isBlank(senderEmail)) {
valid = false;
if (verbose) {
System.out.println("Missing env var: READSTACK_SMTP_EMAIL");
}
}
if (isBlank(senderPassword)) {
valid = false;
if (verbose) {
System.out.println("Missing SMTP password: set READSTACK_SMTP_PASSWORD or store it in macOS Keychain.");
}
}
if (recipientEmails.isEmpty()) {
valid = false;
if (verbose) {
System.out.println("Missing recipient configuration: set READSTACK_RECIPIENT_EMAILS or READSTACK_KINDLE_EMAIL.");
}
}
if (!valid && verbose) {
System.out.println("EPUB delivery not configured, skipping.");
System.out.println("Recommended local setup:");
System.out.println(" 1. Edit .env if you need to change the sender or recipients.");
System.out.println(" 2. Store the Gmail app password in Keychain:");
if (!isBlank(senderEmail)) {
System.out.println(" security add-generic-password -a \"" + senderEmail + "\" -s \"" + keychainService + "\" -w");
} else {
System.out.println(" security add-generic-password -a \"your-gmail@gmail.com\" -s \"" + keychainService + "\" -w");
}
System.out.println(" 3. If your runtime cannot read macOS Keychain, set READSTACK_SMTP_PASSWORD in local .env as a fallback.");
System.out.println(" 4. Run: ./readstack <substack-url> --send");
}
return valid;
}
private static String getSmtpPassword() {
// Preference order:
// 1. Explicit env/.env password
// 2. macOS Keychain lookup
//
// This lets local development stay simple while still supporting a safer
// no-password-in-dotenv setup on macOS.
String configuredPassword = ReadstackConfig.get("READSTACK_SMTP_PASSWORD");
if (!isBlank(configuredPassword)) {
return configuredPassword;
}
return lookupPasswordInKeychain(ReadstackConfig.get("READSTACK_SMTP_EMAIL"));
}
private static List<String> getRecipientEmails() {
// The multi-recipient variable is the current path. The legacy Kindle-only
// variable is still supported so old local setups do not break immediately.
String configuredRecipients = ReadstackConfig.get("READSTACK_RECIPIENT_EMAILS");
if (!isBlank(configuredRecipients)) {
List<String> recipients = new ArrayList<>();
for (String recipient : configuredRecipients.split(",")) {
String trimmed = recipient.trim();
if (!isBlank(trimmed) && !recipients.contains(trimmed)) {
recipients.add(trimmed);
}
}
if (!recipients.isEmpty()) {
return recipients;
}
}
String legacyRecipient = ReadstackConfig.get("READSTACK_KINDLE_EMAIL");
if (!isBlank(legacyRecipient)) {
return Arrays.asList(legacyRecipient.trim());
}
return List.of();
}
private static String lookupPasswordInKeychain(String senderEmail) {
// Keychain access is macOS-specific and can fail under some sandboxes. In those
// cases we return an empty string and let validation explain the fallback.
if (isBlank(senderEmail) || !isMac()) {
return "";
}
ProcessBuilder pb = new ProcessBuilder(
"security",
"find-generic-password",
"-a",
senderEmail,
"-s",
getKeychainService(),
"-w"
);
try {
Process process = pb.start();
// We bound the wait so a stuck `security` process does not hang the entire
// CLI. Delivery should fail fast rather than appear frozen.
boolean finished = process.waitFor(5, TimeUnit.SECONDS);
if (!finished) {
process.destroyForcibly();
return "";
}
if (process.exitValue() != 0) {
return "";
}
String password = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8).trim();
return password;
} catch (Exception e) {
return "";
}
}
private static String getKeychainService() {
// The service name is configurable mainly so users can manage multiple Gmail
// senders without colliding entries in the same macOS keychain.
String service = ReadstackConfig.get("READSTACK_SMTP_KEYCHAIN_SERVICE");
return isBlank(service) ? "readstack-smtp" : service;
}
private static boolean isMac() {
return System.getProperty("os.name").toLowerCase().contains("mac");
}
private static boolean isBlank(String value) {
return value == null || value.isBlank();
}
}