-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathswift-zerosmtp.swift
More file actions
95 lines (82 loc) · 2.68 KB
/
swift-zerosmtp.swift
File metadata and controls
95 lines (82 loc) · 2.68 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
// swift-zerosmtp.swift
/**
* Swift 6.0+ Swift-SMTP 7.0 - ZeroSMTP mx.msgwing.com:465 SSL/TLS
* Production-ready | Let's Encrypt | Actors, macros, async/await
* NO allowUnsafeCertificates
*/
import Foundation
import SMTP
@main
struct ZeroSMTPMailer {
static func main() async {
let config = EmailConfig(
username: ProcessInfo.processInfo.environment["USERNAME"] ?? "your-username",
password: ProcessInfo.processInfo.environment["PASSWORD"] ?? "your-password",
from: ProcessInfo.processInfo.environment["FROM"] ?? "sender@example.com",
to: ProcessInfo.processInfo.environment["TO"] ?? "recipient@example.com",
subject: ProcessInfo.processInfo.environment["SUBJECT"] ?? "Test Email from ZeroSMTP"
)
let mailer = MailerActor(config: config)
let result = await mailer.sendEmail()
switch result {
case .success:
print("Email sent successfully")
exit(0)
case .failure(let error):
fputs("Error: \(error)\n", stderr)
exit(1)
}
}
}
struct EmailConfig {
let username: String
let password: String
let from: String
let to: String
let subject: String
}
enum MailResult {
case success
case failure(String)
}
actor MailerActor {
private let config: EmailConfig
init(config: EmailConfig) {
self.config = config
}
func sendEmail() async -> MailResult {
do {
let smtp = SMTP(
hostname: "mx.msgwing.com",
email: config.username,
password: config.password,
port: 465,
tlsMode: .requireTLS,
tlsConfiguration: nil // uses system trust store
)
let from = Mail.User(name: "ZeroSMTP", email: config.from)
let to = Mail.User(email: config.to)
let mail = Mail(
from: from,
to: [to],
subject: config.subject,
text: "Hello from ZeroSMTP! This is plain text.",
additionalHeaders: [
"Content-Type": "text/plain; charset=UTF-8"
]
)
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
smtp.send(mail) { error in
if let error = error {
continuation.resume(throwing: error)
} else {
continuation.resume()
}
}
}
return .success
} catch {
return .failure("SMTP error: \(error)")
}
}
}