Faizan Ullah
Faizan Ullah

Reputation: 13

Ios Mail sending using mailcore

I am trying to send mail from yesterday but failed to send. always getting this error Error sending email: Error Domain=MCOErrorDomain Code=1 "A stable connection to the server could not be established." UserInfo={NSLocalizedDescription=A stable connection to the server could not be established.}

  NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(self.emailimage)];
//Create a base64 string representation of the data using NSData+Base64
NSString *base64String = [imageData base64EncodedString];

//userdefaults
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *userName = [prefs stringForKey:@"username"];
NSString *password = [prefs stringForKey:@"password"];



MCOSMTPSession *smtpSession = [[MCOSMTPSession alloc] init];

smtpSession.hostname =@"smtp.gmail.com";
//
smtpSession.port = 465;

smtpSession.username =userName;
smtpSession.password =password;
smtpSession.authType = MCOAuthTypeSASLPlain;
smtpSession.connectionType =MCOConnectionTypeStartTLS;

MCOMessageBuilder *builder = [[MCOMessageBuilder alloc] init];
MCOAddress *from1 = [MCOAddress addressWithDisplayName:@""
                                               mailbox:userName];
MCOAddress *to1 = [MCOAddress addressWithDisplayName:nil
                                            mailbox:self.to.text];
[[builder header] setFrom:from1];
[[builder header] setTo:@[to1]];
[[builder header] setSubject:self.subject.text];
NSDate *now = [NSDate date];

 double seconds1 = [now timeIntervalSince1970];
NSNumber *seconds = [NSNumber numberWithInteger:seconds1];
NSLog(@"id is=======================%@",seconds);
AppDelegate *tokenD = [[UIApplication sharedApplication]delegate];
  NSLog(@"token in Composeviewcontroller %@",tokenD.Dtoken);
NSString *htmlbody1;

htmlbody1=@"abc";
[builder setHTMLBody:htmlbody1];
MCOAttachment *attachment = [MCOAttachment attachmentWithContentsOfFile:self.filename];
[builder addAttachment:attachment];

NSData * rfc822Data = [builder data];


MCOSMTPSendOperation *sendOperation =
[smtpSession sendOperationWithData:rfc822Data];
[sendOperation start:^(NSError *error) {
    NSLog(@"Entered");
    if(error) {

        NSLog(@"Error sending email: %@", error);
    }

    else {

        NSLog(@"Successfully sent email!");
    }
}];

Always going in error block and error and getting error Error sending email: Error Domain=MCOErrorDomain Code=1

Upvotes: 1

Views: 921

Answers (2)

Bharat
Bharat

Reputation: 3198

Please try this solution, You might get resolve your issue or someone get solution

Swift 5, iOS 13, Xcode Version 11.3.1 (11C504)

Also Need to Disable Captcha :  [https://accounts.google.com/DisplayUnlockCaptcha][1]

Response: Successfully sent email!

Here is the perfect solution:

    @IBAction func btnSendMailClicked(_ sender: UIButton) {

    print(#function)
    let smtpSession = MCOSMTPSession()
    smtpSession.hostname = "smtp.gmail.com"
    smtpSession.username = "[email protected]"
    smtpSession.password = "password" //You can create [App Password from gmail setting][1] 

    smtpSession.port = 587 //25
    smtpSession.authType = MCOAuthType.saslPlain
    smtpSession.connectionType = MCOConnectionType.startTLS
    smtpSession.isCheckCertificateEnabled = false

    smtpSession.connectionLogger = {(connectionID, type, data) in
        if data != nil {
            if let string = NSString(data: data!, encoding: String.Encoding.utf8.rawValue){
                NSLog("Connectionlogger: \(string)")
            }
        }
    }

    let builder = MCOMessageBuilder()
    builder.header.to = [MCOAddress(displayName: "Swifty Developers", mailbox: "[email protected]")!]
    builder.header.from = MCOAddress(displayName: "Mehul Parmar", mailbox: "[email protected]")
    builder.header.subject = "My message"
    builder.htmlBody = "Yo Rool, this is a test message!"

    let rfc822Data = builder.data()
    let sendOperation = smtpSession.sendOperation(with: rfc822Data)
    sendOperation?.start { (error) -> Void in
        if (error != nil) {
            NSLog("Error sending email: \(String(describing: error))")
        } else {
            NSLog("Successfully sent email!")
        }
    }
}

Upvotes: 0

Mr.Rebot
Mr.Rebot

Reputation: 6791

You should try using MCOConnectionTypeTLS for smtpSession.connectionType

MCOConnectionTypeStartTLS
on the same TCP connection.
Declared In MCOConstants.h.

MCOConnectionTypeTLS
Encrypted connection usingTLS/SSL.
Declared In MCOConstants.h.

source of reference

And comment out authType:

//smtpSession.authType = MCOAuthTypeSASLPlain;

Upon further research in this thread they removed the authType line and change the MCOConnectionTypeStartTLS to MCOConnectionTypeTLS.

Upvotes: 1

Related Questions