I’m trying to connect to POP3 Server using Swift. Here is my code, I have used InputStream and OutputStream.
import Foundation
class Pop3Client{
var inputStream: InputStream!
var outputStream: OutputStream!
init(host: String,port: Int){
Stream.getStreamsToHost(withName: host, port: port, inputStream: &inputStream, outputStream: &outputStream)
if inputStream == nil || outputStream == nil {
// Handle error, e.g., print an error message and return
print("Failed to initialize streams.")
return
}
guard inputStream.streamStatus == .open else {
print("Input stream is not open.")
return
}
inputStream.schedule(in: .current, forMode: .default)
outputStream.schedule(in: .current, forMode: .default)
inputStream.open()
outputStream.open()
}
deinit {
inputStream.close()
outputStream.close()
}
func sendCommand(command: String){
let data = "(command)rn".data(using: .utf8)!
let bytes = data.withUnsafeBytes { outputStream.write($0.baseAddress!.assumingMemoryBound(to: UInt8.self), maxLength: data.count) }
print("WRITTEN (bytes)")
usleep(1000000)
}
func readResponse() -> String {
var buffer = [UInt8](repeating: 0, count: 4096)
var response = ""
// Check if the input stream is open before reading
guard inputStream.streamStatus == .open else {
print("Input stream is not open.")
return response
}
repeat {
let bytesRead = inputStream.read(&buffer, maxLength: buffer.count)
if bytesRead > 0 {
if let str = String(bytes: buffer, encoding: .utf8) {
response += str
}
} else if bytesRead == 0 {
// No more data available to read
break
} else if bytesRead == -1 {
// Handle error, e.g., print an error message
if let error = inputStream.streamError {
print("Error reading from stream: (error)")
} else {
print("Unknown error reading from stream.")
}
break
}
} while inputStream.hasBytesAvailable
return response
}
func login(username: String, password: String) {
sendCommand(command:"USER (username)")
print(readResponse())
sendCommand(command:"PASS (password)")
print(readResponse())
}
func listMessages() {
sendCommand(command:"LIST")
print(readResponse())
}
func quit() {
sendCommand(command:"QUIT")
print(readResponse())
}
}
let pop3Client = Pop3Client(host: "pop.mail.yahoo.com", port: 995)
pop3Client.login(username: "EMAIL_HERE", password: "PASSWORD_HERE")
pop3Client.listMessages()
pop3Client.quit()
Here is my output when I try to connnect to yahoo POP3 server
Input stream is not open.
WRITTEN -1
Input stream is not open.
WRITTEN -1
Input stream is not open.
WRITTEN -1
Input stream is not open.
WRITTEN -1
Input stream is not open.
2
Answers
I think it’s because there is no "TLS" connection…
edit your init like this: