Skip to content

Commit

Permalink
fix(attachment:filename): fix the mime filename header
Browse files Browse the repository at this point in the history
the bug happens only for filenames that contain non ascii characters like latin or german umlauts

now the content-type name and content-disposition filename behaves correctly according to the rfc2231 and rfc2047
  • Loading branch information
sassman committed Apr 24, 2020
1 parent 4937eca commit 112ba14
Showing 1 changed file with 33 additions and 2 deletions.
35 changes: 33 additions & 2 deletions Sources/PerfectSMTP/PerfectSMTP.swift
Original file line number Diff line number Diff line change
Expand Up @@ -248,14 +248,45 @@ public class EMail {
print("\(data.utf8.count) bytes attached")
}
// pack it up to an MIME part
return "--\(boundary)\r\nContent-Type: \(mimeType); name=\"\(file)\"\r\n"
let filename = paramterRfc2231(something: file)
let name = contentTypefilenameParameter(something: file)
return "--\(boundary)\r\n"
+ "Content-Disposition: \(disposition);\r\n"
+ " filename*=\(filename)\r\n"
+ "Content-Type: \(mimeType);\r\n"
+ " name=\"\(name)\"\r\n"
+ "Content-Transfer-Encoding: base64\r\n"
+ "Content-Disposition: \(disposition); filename=\"\(file)\"\r\n\r\n\(data)\r\n"
+ "\r\n\(data)\r\n"
} catch {
return ""
}
}

/// https://www.ietf.org/rfc/rfc2047.txt
/// encode a string to url encode conform string
/// - parameters:
/// - something: a string to be encoded
/// - returns:
/// base64 but rfc2047 conform string
private func contentTypefilenameParameter(something: String) -> String {
let something = something.base64Encoded()!
// from rfc2047 encoded-word = "=?" charset "?" encoding "?" encoded-text "?="
// Q is "Quoted-Printable" content-transfer-encoding defined in RFC 2045
// B is Base64
return "=?utf-8?B?\(something)?="
}

/// https://tools.ietf.org/html/rfc2231
/// encode a string to url encode conform string
/// - parameters:
/// - something: a string to be encoded
/// - returns:
/// url encoded string
private func paramterRfc2231(something: String) -> String {
let something = something.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
return "utf-8''\(something)"
}

/// encode a file by base64 method
/// - parameters:
/// - path: full path of the file to encode
Expand Down

0 comments on commit 112ba14

Please sign in to comment.