send email from swift osx application

swift send email without mfmailcomposeviewcontroller
xcode send email
swift send email with attachment
nssharingservice
ios send email programmatically in background
swift send email automatically
swiftui send email
swift send email gmail

I am facing problem on sending mail from my osx swift application. To send mail i used the below code

import Foundation
import Cocoa


class sendemail : NSObject, NSSharingServiceDelegate{

func sendEmail()  throws
{
    print("enter email sending")
    let body = "This is an email for auto testing throug code."
    let shareItems = [body] as NSArray

    let service = NSSharingService(named: NSSharingServiceNameComposeEmail)

    service?.delegate = self
    service?.recipients = ["abc@dom.com"]

    let subject = "Vea Software"
    service?.subject = subject

    service?.performWithItems(shareItems as [AnyObject])
}

}

i have found the source form this link:https://www.veasoftware.com/posts/send-email-in-swift-xcode-62-os-x-1010-tutorial

But it is not working.

I also tried to send mail from terminal following this instructions:

http://www.developerfiles.com/how-to-send-emails-from-localhost-mac-os-x-el-capitan/

it says :

postfix/postfix-script: fatal: the Postfix mail system is not running

please help me.

I can send mail from my mac mail app manually which is configured.

I am using

xcode 7.3, osx el captain and swift 2.2

This works for me:

class SendEmail: NSObject {
    static func send() {
        let service = NSSharingService(named: NSSharingServiceNameComposeEmail)!
        service.recipients = ["abc@dom.com"]
        service.subject = "Vea software"

        service.performWithItems(["This is an email for auto testing through code."])
    }
}

Usage:

SendEmail.send()

How to send an email, In the MessageUI framework lies the MFMailComposeViewController class, which handles sending emails from your app. You get to set the  let errpipe = Pipe() // should remain empty let outpipe = Pipe() // should remain empty (but if you use other options you may get some text) let inpipe = Pipe() // will be used to transfer the mail to sendmail // Setup the process that will send the mail let process = Process() if #available(OSX 10.13, *) { process.executableURL = URL(fileURLWithPath: "/usr/sbin/sendmail") } else { process.launchPath = "/usr/sbin/sendmail" } process.arguments = options process.standardError = errpipe process

Swift 4.2:

class SendEmail: NSObject {
    static func send() {
        let service = NSSharingService(named: NSSharingService.Name.composeEmail)!
        service.recipients = ["email@yourEmail.eu"]
        service.subject = "Email Subject"

        service.perform(withItems: ["Email Content"])
    }
}

Usage: SendEmail.send()

Send Email iOS Tutorial, It is possible to compose and send an email from inside an app using the and a subject. This tutorial is made with Xcode 11 and built for iOS 13. Sending Email through your app in Swift First of all, we need to import the MessageUI module. Second, we need to specify that the View Controller will conform to the MFMailComposeViewControllerDelegate protocol. In order to send Email through your app in Swift, you need a few things :

We solved this "the hard way" by not using the shared services, but the postfix utility. Note that postfix must be running and correctly configured before the following code can take effect.

Why do this the hard way? well, it is a slightly more 'universal' solution that should work (or can be modified easily) on other platforms than macOS. Also, it does not depend on 'mail'.

Note that this also uses our Log facility, but you should be able to easily extract the code you need.

/// This queue/thread will be used to transfer the mails.

fileprivate let mailQueue = DispatchQueue.global(qos: .background)


/// Sends an email using the postfix unix utility.
///
/// - Note: Ths function only works if postfix is running (and set up correctly)
///
/// - Parameters:
///   - mail: The email to be transmitted. It should -as a minimum- contain the To, From and Subject fields.
///   - domainName: The domain this email is sent from, used for logging purposes only.

public func sendEmail(_ mail: String, domainName: String) {


    // Do this on a seperate queue in the background so this operation is non-blocking.

    mailQueue.async { [mail, domainName] in

        // Ensure the mail is ok

        guard let utf8mail = mail.data(using: .utf8), utf8mail.count > 0 else {
            Log.atDebug?.log("No mail present")
            return
        }

        let options: Array<String> = ["-t"] // This option tells sendmail to read the from/to/subject from the email string itself.

        let errpipe = Pipe() // should remain empty
        let outpipe = Pipe() // should remain empty (but if you use other options you may get some text)
        let inpipe = Pipe()  // will be used to transfer the mail to sendmail


        // Setup the process that will send the mail

        let process = Process()
        if #available(OSX 10.13, *) {
            process.executableURL = URL(fileURLWithPath: "/usr/sbin/sendmail")
        } else {
            process.launchPath = "/usr/sbin/sendmail"
        }
        process.arguments = options
        process.standardError = errpipe
        process.standardOutput = outpipe
        process.standardInput = inpipe


        // Start the sendmail process

        let data: Data
        do {

            Log.atDebug?.log("\n\(mail)")


            // Setup the data to be sent

            inpipe.fileHandleForWriting.write(utf8mail)


            // Start the sendmail process

            if #available(OSX 10.13, *) {
                try process.run()
            } else {
                process.launch()
            }


            // Data transfer complete

            inpipe.fileHandleForWriting.closeFile()


            // Set a timeout. 10 seconds should be more than enough.

            let timeoutAfter = DispatchTime(uptimeNanoseconds: DispatchTime.now().uptimeNanoseconds + UInt64(10000) * 1000000)


            // Setup the process timeout on another queue

            DispatchQueue.global().asyncAfter(deadline: timeoutAfter) {
                [weak process] in
                Log.atDebug?.log("Sendmail Timeout expired, process \(process != nil ? "is still running" : "has exited already")")
                process?.terminate()
            }


            // Wait for sendmail to complete

            process.waitUntilExit()

            Log.atDebug?.log("Sendmail terminated")


            // Check termination reason & status

            if (process.terminationReason == .exit) && (process.terminationStatus == 0) {

                // Exited OK, return data

                data = outpipe.fileHandleForReading.readDataToEndOfFile()

                if data.count > 0 {
                    Log.atDebug?.log("Unexpectedly read \(data.count) bytes from sendmail, content: \(String(data: data, encoding: .utf8) ?? "")")
                } else {
                    Log.atDebug?.log("Sendmail completed without error")
                }

            } else {

                // An error of some kind happened

                Log.atError?.log("Sendmail process terminations status = \(process.terminationStatus), reason = \(process.terminationReason.rawValue )")

                let now = dateFormatter.string(from: Date())

                Log.atError?.log("Sendmail process failure, check domain (\(domainName)) logging directory for an error entry with timestamp \(now)")


                // Error, grab all possible output and create a file with all error info

                let e = errpipe.fileHandleForReading.readDataToEndOfFile()
                let d = outpipe.fileHandleForReading.readDataToEndOfFile()

                let dump =
                """
                Process Termination Reason: \(process.terminationReason.rawValue)
                Sendmail exit status: \(process.terminationStatus)
                Details:
                - Sendmail Executable  : /usr/sbin/sendmail
                - Sendmail Options     : -t
                - Sendmail Timeout     : 10,000 mSec
                - Sendmail Error output: \(e.count) bytes
                - Sendmail Output      : \(d.count) bytes
                Below the output of sendmail is given in the following block format:
                (----- Email input -----)
                ...
                (----- Standard Error -----)
                ...
                (----- Standard Out -----)
                ...
                (----- End of output -----)

                (----- Email input -----)
                \(mail)
                (----- Standard Error -----)
                \(String(bytes: e, encoding: .utf8) ?? "")
                (----- Standard Out -----)
                \(String(bytes: d, encoding: .utf8) ?? "")
                (----- End of output -----)
                """

                let errorFileName = "sendmail-error-log-" + now
                if
                    let errorFileUrl = Urls.domainLoggingDir(for: domainName)?.appendingPathComponent(errorFileName).appendingPathExtension("txt"),
                    let dumpData = dump.data(using: .utf8),
                    ((try? dumpData.write(to: errorFileUrl)) != nil) {
                } else {
                    Log.atError?.log("Cannot create sendmail error file, content is: \n\(dump)\n")
                }
            }

        } catch let error {

            Log.atError?.log("Exception occured during sendmail execution, message = \(error.localizedDescription)")
        }
    }
}

This routine should be called with a string formatted like:

    let email: String =
    """
    To: \(emailAddress)
    From: \(fromAddress)
    Content-Type: text/html;
    Subject: Confirm Account Creation at \(domain.name)\n
    \(message)
    """

How To Send an Email From Your App - Swift, Use this view controller to display a standard email interface inside your app. If the user opts to send the message, the message is queued in the user's Mail app outbox. dismiss view controllers, see View Controller Programming Guide for iOS. Xcode · Swift · Swift Playgrounds · TestFlight · Documentation · Videos  Swift version: 5.2. In the MessageUI framework lies the MFMailComposeViewController class, which handles sending emails from your app. You get to set the recipients, message title and message text, but you don't get to send it – that's for the user to tap themselves. Make sure you add import MessageUI to any Swift file that uses this code, and you’ll also need to conform to the MFMailComposeViewControllerDelegate protocol.

MFMailComposeViewController, xcode - send email from swift osx application - Stack Overflow. xcode swift php - Prevent header from email when sending from swift mailer in symf php email  Knowing how to send attachments in the email is very important since most of the application has sharing features. Hence having hands-on experience is important. In this post, we will be seeing how to send an attachment in the mail using Swift.

Sending Email With Swift, How to develop an application for sending Emails using Swift language.You also come to know the XCode tool and how it is used to on create  How to send emails in your iOS Application using: MFMailComposeViewController Have you wanted to send an e-mail from your app and pre-populate the fields like the recipient, subject, or body text

How to Send Email using MFMailComposeView in Swift 4.1?, I have an IOS Swift/Xcode project that a user must register with a valid email address. I would like to use that email to send them a registration  Steps to send email with attachment in swift 1: Create a single view application template project in xcode and name it “ SendMailAttachment “ 2: Open “Main,storyboard” file and first change background color for the view and drag a UIButton on to the view.

Comments
  • thanks a lot for your help. But it does not work here ... :( .... is this necessary to setup anything like postmail to run this successfully?
  • Works for me with no extra setup required. Thanks
  • I had the same issue. What needs to be in place is that Apple's Mail is the email client of your choice.