Не удалось использовать Swift для внедрения электронной почты в приложении
Я хочу использовать swift для внедрения электронной почты в приложении. Когда я нажимаю кнопку, открывается окно электронной почты. Однако я не могу отправить свою электронную почту. Более того, после того, как я нажму кнопку "Отменить удаление", я не могу вернуться к исходному экрану.
import UIkit
import MessageUI
class Information : UIViewController, MFMailComposeViewControllerDelegate{
var myMail: MFMailComposeViewController!
@IBAction func sendReport(sender : AnyObject) {
if(MFMailComposeViewController.canSendMail()){
myMail = MFMailComposeViewController()
//myMail.mailComposeDelegate
// set the subject
myMail.setSubject("My report")
//To recipients
var toRecipients = ["[email protected]"]
myMail.setToRecipients(toRecipients)
//CC recipients
var ccRecipients = ["[email protected]"]
myMail.setCcRecipients(ccRecipients)
//CC recipients
var bccRecipients = ["[email protected]"]
myMail.setBccRecipients(ccRecipients)
//Add some text to the message body
var sentfrom = "Email sent from my app"
myMail.setMessageBody(sentfrom, isHTML: true)
//Include an attachment
var image = UIImage(named: "Gimme.png")
var imageData = UIImageJPEGRepresentation(image, 1.0)
myMail.addAttachmentData(imageData, mimeType: "image/jped", fileName: "image")
//Display the view controller
self.presentViewController(myMail, animated: true, completion: nil)
}
else{
var alert = UIAlertController(title: "Alert", message: "Your device cannot send emails", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
func mailComposeController(controller: MFMailComposeViewController!,
didFinishWithResult result: MFMailComposeResult,
error: NSError!){
switch(result.value){
case MFMailComposeResultSent.value:
println("Email sent")
default:
println("Whoops")
}
self.dismissViewControllerAnimated(true, completion: nil)
}
}
Ответы
Ответ 1
Поскольку вы не задали текущий контроллер представления как mailComposeDelegate
myMail
, метод mailComposeController:didFinishWithResult
не вызывается. После инициализации myMail
обязательно добавьте:
myMail.mailComposeDelegate = self
и вам будет хорошо идти
Ответ 2
Если кто-то ищет параметр MFMailCompose, вот что я сделал для отправки с использованием SMTP-серверов Gmail.
- Загрузите zip этого репо: https://github.com/jetseven/skpsmtpmessage
- Перетащите файлы под SMTPLibrary в проект XCode.
- Создайте новый файл заголовка -
MyApp-Briding-Header.h
- Замените новый заголовочный файл следующим образом:
#import "Base64Transcoder.h"
#import "HSK_CFUtilities.h"
#import "NSData+Base64Additions.h"
#import "NSStream+SKPSMTPExtensions.h"
#import "SKPSMTPMessage.h"
- Перейдите в Project (Цели > MyApp слева)/Build Settings/Swift Compiler - Генерация кода
- Добавить путь в заголовочный файл в
Objective-C Briding Header
→ Debug
(т.е. MyApp/MyApp-Bridging-Header.h
- Перейти к разделу "Проект/Сборка фаз/Источники компиляции"
-
Выберите все файлы .m и нажмите "Enter". Введите -fno-objc-arc
и нажмите enter.
-
Используйте этот код для отправки электронной почты:
var mail = SKPSMTPMessage()
mail.fromEmail = "[email protected]"
mail.toEmail = "[email protected]"
mail.requiresAuth = true
mail.login = "[email protected]"
mail.pass = "password"
mail.subject = "test subject"
mail.wantsSecure = true
mail.relayHost = "smtp.gmail.com"
mail.relayPorts = [587]
var parts: NSDictionary = [
"kSKPSMTPPartContentTypeKey": "text/plain; charset=UTF-8",
"kSKPSMTPPartMessageKey": "test message",
]
mail.parts = [parts]
mail.send()
Надеюсь, это поможет кому-то. Я не хотел использовать параметр MFMailCompose, потому что я не хотел запрашивать пользователя.
Ответ 3
Вот как я написал свою электронную почту с прикрепленным файлом PDF.
Чтобы проверить этот пример, вам нужно перетащить образец PDF с именем "All_about_tax.pdf"
@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 id here"])
//Set the subject
mailComposer.setSubject("Tax info 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)
}