如何在iOS5的后台向收件人发送电子邮件?

时间:2011-11-10 16:54:19

标签: iphone email background ios5

在iPhone应用中,我想向忘记密码的人发送电子邮件。我想在后台发送邮件(不能使用MFMailComposeViewController),也不能将应用程序推送到后台。有没有办法实现这个目标?

8 个答案:

答案 0 :(得分:10)

执行此操作的最佳方法是使用SKPSMTPMessage。您可以从这里下载它:https://github.com/jetseven/skpsmtpmessage这是我以前在iOS应用程序中使用“忘记密码”解决方案时使用的一个非常简单的解决方案。要实现,只需将下载的文件拖放到您的应用程序中,#import将“SKPSMTPMessage.h”拖到您的类中,并实现以下代码:

·H

#import "SKPSMTPMessage.h"

@interface SomeView : UIViewController <SKPSMTPMessageDelegate> {

}

- (IBAction)forgotPassword;

的.m

- (IBAction)forgotPassword {
SKPSMTPMessage *forgotPassword = [[SKPSMTPMessage alloc] init];
[forgotPassword setFromEmail:@"some-email@gmail.com"];  // Change to your email address
[forgotPassword setToEmail:@"user-email@gmail.com"]; // Load this, or have user enter this
[forgotPassword setRelayHost:@"smtp.gmail.com"];
[theMessage setRequiresAuth:YES]; // GMail requires this
[forgotPassword setLogin:@"some-email@gmail.com"]; // Same as the "setFromEmail:" email
[forgotPassword setPass:@"password"]; // Password for the Gmail account that you are sending from
[forgotPassword setSubject:@"Forgot Password: My App"]; // Change this to change the subject of the email
[forgotPassword setWantsSecure:YES]; // Gmail Requires this
[forgotPassword setDelegate:self]; // Required

NSString *newpassword = @"helloworld";

NSString *message = [NSString stringWithFormat:@"Your password has been successfully reset. Your new password: %@", newpassword];
NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:@"text/plain", kSKPSMTPPartContentTypeKey, message, kSKPSMTPPartMessageKey, @"8bit" , kSKPSMTPPartContentTransferEncodingKey, nil];

[forgotPassword setParts:[NSArray arrayWithObjects:plainPart, nil]];
[forgotPassword send];
}

还要确保在.m中包含以下方法。您可以根据要向用户显示的内容更改UIAlertView的内容。

- (void)messageSent:(SKPSMTPMessage *)message {
    NSLog(@"Message Sent");

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Password Reset" message:@"Check your email for your new password." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
}

- (void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error {
    NSLog(@"Message Failed With Error(s): %@", [error description]);
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"There was an error reseting your password. Please try again later." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
}

在此之前,您还需要执行以下操作。 你的目标 - &gt;获取信息 - &gt;构建 - &gt;所有配置 - &gt;其他链接标志:“ - ObjC” 如果您需要帮助,请参阅http://developer.apple.com/qa/qa2006/qa1490.html

编辑: *还必须添加CFNetwork.framework才能实现此功能! *

如果您还有其他问题,请与我们联系。

谢谢, 雅各布

答案 1 :(得分:5)

您无法使用MFMailComposeViewController执行此操作。没有API将允许您在没有看到的情况下代表用户发送电子邮件或任何类型的消息。

我唯一看到的是拨打您的服务器,服务器发送电子邮件,如下所示:

NSURLRequest requestWithURL:[NSURL urlWithString:@"http://server.com/send_passcode?to=email@lala.com"]];

答案 2 :(得分:2)

未经用户接受,您无法发送短信/电子邮件。但是互联网上有很多可以发送短信/电子邮件的网络服务。我想一些应用程序使用这些服务或使用自己的。

答案 3 :(得分:2)

CAN 在后台发送电子邮件(不使用默认的MFMail控制器)。但是你仍然需要用户填写任何形式(或你想要发送电子邮件的内容)并让他们点击“发送”。

以下是关于如何操作的帖子。它包括代码和图像。

Locking the Fields in MFMailComposeViewController

P.S。这是有效的,Apple已经批准了超过10个使用此代码/方法的应用程序。

答案 4 :(得分:0)

如果您想在不设置SMTP客户端的情况下发送电子邮件,请参阅下面的PostageApp评论,您可以查看PostageKit包装器以使用PostageApp服务。让我们可靠地发送包含几行代码的电子邮件。

https://github.com/twg/PostageKit

答案 5 :(得分:0)

可能是您应该实现向用户发送电子邮件的PHP脚本。在ios中,您可以在NSURLConnection中使用POST方法来调用PHP脚本。您可以在Google上找到许多脚本,向用户发送电子邮件。

答案 6 :(得分:0)

下载SKPSMTP库并导入

#import "SKPSMTPMessage.h"
#import "NSData+Base64Additions.h"


-(IBAction)btnRecoverClicked:(id)Sender;

然后实现在后台发送邮件的方法。

-(IBAction) btnRecoverClicked:(id)sender {
    NSString *str=@"Your password is:";
    NSString *strUserPassword=[NSString stringWithFormat:@"%@ %@",str,struserPassword];
    NSLog(@"Start Sending");
    SKPSMTPMessage *emailMessage = [[SKPSMTPMessage alloc] init];
    emailMessage.fromEmail = @"XXXXX"; //sender email address
    emailMessage.toEmail = struserEmail;  //receiver email address
    emailMessage.relayHost = @"smtp.gmail.com";
    //emailMessage.ccEmail =@"your cc address";
    //emailMessage.bccEmail =@"your bcc address";
    emailMessage.requiresAuth = YES;
    emailMessage.login = @"xxxxxxxx"; //sender email address
    emailMessage.pass = @"XXXXXXX"; //sender email password
    emailMessage.subject =@"Password Recovery";
    emailMessage.wantsSecure = YES;
    emailMessage.delegate = self; // you must include <SKPSMTPMessageDelegate> to your class
    NSString *messageBody = [NSString stringWithFormat:@"Your password is: %@",struserPassword]
    ;
    //for example :   NSString *messageBody = [NSString stringWithFormat:@"Tour Name: %@\nName: %@\nEmail: %@\nContact No: %@\nAddress: %@\nNote: %@",selectedTour,nameField.text,emailField.text,foneField.text,addField.text,txtView.text];
    // Now creating plain text email message
    NSDictionary *plainMsg = [NSDictionary
                              dictionaryWithObjectsAndKeys:@"text/plain",kSKPSMTPPartContentTypeKey,
                              messageBody,kSKPSMTPPartMessageKey,@"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
    emailMessage.parts = [NSArray arrayWithObjects:plainMsg,nil];
    //in addition : Logic for attaching file with email message.
    /*
     NSString *filePath = [[NSBundle mainBundle] pathForResource:@"filename" ofType:@"JPG"];
     NSData *fileData = [NSData dataWithContentsOfFile:filePath];
     NSDictionary *fileMsg = [NSDictionary dictionaryWithObjectsAndKeys:@"text/directory;\r\n\tx-
     unix-mode=0644;\r\n\tname=\"filename.JPG\"",kSKPSMTPPartContentTypeKey,@"attachment;\r\n\tfilename=\"filename.JPG\"",kSKPSMTPPartContentDispositionKey,[fileData encodeBase64ForData],kSKPSMTPPartMessageKey,@"base64",kSKPSMTPPartContentTransferEncodingKey,nil];
     emailMessage.parts = [NSArray arrayWithObjects:plainMsg,fileMsg,nil]; //including plain msg and attached file msg
     */
    [emailMessage send];
    // sending email- will take little time to send so its better to use indicator with message showing sending...
}

处理成功和失败使用

-(void)messageSent:(SKPSMTPMessage *)message{
    NSLog(@"delegate - message sent");
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message sent to your mail." message:nil delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];
    [alert show];
}

-(void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error{
    // open an alert with just an OK button
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error!" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];
    [alert show];
    NSLog(@"delegate - error(%d): %@", [error code], [error localizedDescription]);
}

答案 7 :(得分:0)

https://github.com/troyz/MailUtil

我已经使用上面的库在后台发送邮件,因此可以正常工作。

pod "MailUtil", :git => 'https://github.com/troyz/MailUtil.git', :tag => '0.1.0'

快速代码在这里:

import MailUtil

SendEmailOperation.setupConfig(withServer: "smtp.foo.com", withFrom: "foo@mailserver.com", withLogin: "foo@mailserver.com", withPassword: "*********")

let operation = SendEmailOperation(to: "foo@mailserver.com", subject: "Hello", body: "world", path: "/selected/path/for/your/file.pdf")

operation?.completionBlock = {
    debugPrint("Mail sent!")
    DispatchQueue.main.async {
         //showMailSentPopup()
   }
}

do {
      try SendEmailOperation.sendEmail(operation)
   } catch {
      debugPrint("Mail could not sent or sending result could not handle - \(error)")
   }