我想发送带有PDF附件的电子邮件。 我创建了PDF文件,然后我做了以下错误我认为:
// locate folder containing pdf file
let documentsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as! String
let pdfFileName = documentsPath.stringByAppendingPathComponent("chart.pdf")
let fileData = NSData(contentsOfFile: pdfFileName)
mc.addAttachmentData(fileData, mimeType: "pdf", fileName: chart)
在发送电子邮件之前,我可以看到附件chart.pdf
,但是当我发送电子邮件时,它是在没有附件的情况下发送的,这是因为我没有正确附加文件。
答案 0 :(得分:12)
您将错误mimeType
传递给addAttachmentData()
。使用application/pdf
代替pdf
。
答案 1 :(得分:4)
我们可以通过电子邮件附上PDF文件并以编程方式发送
Swift 2.2
@IBAction func sendEmail(sender: UIButton)
{
//Check to see the device can send email.
if( MFMailComposeViewController.canSendMail() )
{
print("Can send email.")
let mailComposer = MFMailComposeViewController()
mailComposer.mailComposeDelegate = self
//Set to recipients
mailComposer.setToRecipients(["your email address heres"])
//Set the subject
mailComposer.setSubject("email with document pdf")
//set mail body
mailComposer.setMessageBody("This is what they sound like.", isHTML: true)
if let filePath = NSBundle.mainBundle().pathForResource("All_about_tax", ofType: "pdf")
{
print("File path loaded.")
if let fileData = NSData(contentsOfFile: filePath)
{
print("File data loaded.")
mailComposer.addAttachmentData(fileData, mimeType: "application/pdf", fileName: "All_about_tax.pdf")
}
}
//this will compose and present mail to user
self.presentViewController(mailComposer, animated: true, completion: nil)
}
else
{
print("email is not supported")
}
}
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?)
{
self.dismissViewControllerAnimated(true, completion: nil)
}
答案 2 :(得分:3)
第一个,导入:
import MessageUI
并实施de Email Delegate,例如
public class MyViewController : UIViewController, MFMailComposeViewControllerDelegate { ...
如果您具有文件或Data
类型,则可以使用此功能:
let filePath = NSBundle.mainBundle().pathForResource("chart", ofType: "pdf")
let fileData = NSData(contentsOfFile: filePath)
sendEmail(data:fileData)
快捷键4
func sendEmail(data:Data?){
if( MFMailComposeViewController.canSendMail() ) {
let mailComposer = MFMailComposeViewController()
mailComposer.mailComposeDelegate = self
mailComposer.setToRecipients(["john@stackoverflow.com", "mrmins@mydomain.com", "anotheremail@email.com"])
mailComposer.setSubject("Cotización")
mailComposer.setMessageBody("My body message", isHTML: true)
if let fileData = data {
mailComposer.addAttachmentData(fileData, mimeType: "application/pdf", fileName: "MyFileName.pdf")
}
self.present(mailComposer, animated: true, completion: nil)
return
}
print("Email is not configured")
}
还有compose
:
public func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?){
self.dismiss(animated: true, completion: nil)
print("sent!")
}