[在iPhone应用程序中,我想向忘记密码的人发送电子邮件。我想在后台发送邮件(不能使用MFMailComposeViewController),并且应用程序一定不能推送到后台。有没有办法做到这一点?
最好的方法是使用SKPSMTPMessage。您可以从此处下载它:https://github.com/jetseven/skpsmtpmessage这是我之前在iOS应用中使用“忘记密码”解决方案时使用的非常简单的解决方案。要实现,只需将下载的文件拖到您的应用程序中,将“ SKPSMTPMessage.h” #import
拖入您的类中,并实现以下代码:
。h
#import "SKPSMTPMessage.h"
@interface SomeView : UIViewController <SKPSMTPMessageDelegate> {
}
- (IBAction)forgotPassword;
。m
- (IBAction)forgotPassword {
SKPSMTPMessage *forgotPassword = [[SKPSMTPMessage alloc] init];
[forgotPassword setFromEmail:@"[email protected]"]; // Change to your email address
[forgotPassword setToEmail:@"[email protected]"]; // Load this, or have user enter this
[forgotPassword setRelayHost:@"smtp.gmail.com"];
[theMessage setRequiresAuth:YES]; // GMail requires this
[forgotPassword setLogin:@"[email protected]"]; // 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中包括以下方法。您可以根据要向用户显示的内容来更改UIAlertViews的内容。
- (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];
}
您还需要执行以下操作,然后才能起作用。您的目标->获取信息->构建->所有配置->其他链接标志:“-ObjC”如果您需要帮助,请参见http://developer.apple.com/qa/qa2006/qa1490.html
编辑:* CFNetwork.framework也必须添加才能正常工作! *
让我知道是否还有其他问题。
谢谢,雅各布
您不能使用MFMailComposeViewController
执行此操作。没有API允许您在用户看不见的情况下代表用户发送电子邮件或任何类型的消息。
我唯一看到的是打电话给您的服务器,然后服务器发送电子邮件,如下所示:
NSURLRequest requestWithURL:[NSURL urlWithString:@"http://server.com/[email protected]"]];
未经用户接受,您无法发送SMS /电子邮件。但是互联网上有很多可以发送SMS /电子邮件的Web服务。我猜有些应用使用这些服务或使用自己的服务。
您CAN在后台发送电子邮件(不使用默认的MFMail控制器)。但是您仍然需要用户填写任何表格(或您想通过电子邮件发送的内容),然后让他们单击“发送”。
这是我的相关操作方法。它包括代码和图像。
Locking the Fields in MFMailComposeViewController
P.S。此方法有效,Apple批准了我的超过10个使用此代码/方法的应用程序。
关于下面的PostageApp评论,如果您想发送电子邮件而没有设置SMTP客户端的麻烦,您可以签出PostageKit包装器以使用PostageApp服务。让我们可靠地发送带有几行代码的电子邮件。
[也许您应该实现将向用户发送电子邮件的PHP脚本。在ios中,您可以在NSURLConnection中使用POST方法来调用PHP脚本。您可以在Google上找到许多脚本来向用户发送电子邮件。
下载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]);
}
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: "[email protected]", withLogin: "[email protected]", withPassword: "*********")
let operation = SendEmailOperation(to: "[email protected]", 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)")
}