Created
November 17, 2020 10:40
-
-
Save Ryszardenko/ac90db6d7ffa3dc8d52b4cb52dc085c2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//build.gradle (:app) | |
//implementation 'com.sun.mail:android-mail:1.6.2' | |
//implementation 'com.sun.mail:android-activation:1.6.2' | |
import io.reactivex.Completable | |
import io.reactivex.disposables.Disposable | |
import io.reactivex.schedulers.Schedulers | |
import java.lang.Exception | |
import java.util.* | |
import javax.mail.* | |
import javax.mail.internet.InternetAddress | |
import javax.mail.internet.MimeMessage | |
object EmailService { | |
val email = "your.email@gmail.com" | |
val password = "password" | |
fun sendMail(recipient: String, subject: String, message: String): Disposable { | |
return Completable.create { emitter -> | |
val properties = Properties().also { | |
it["mail.smtp.host"] = "smtp.gmail.com" | |
it["mail.smtp.socketFactory.port"] = "465" | |
it["mail.smtp.socketFactory.class"] = "javax.net.ssl.SSLSocketFactory" | |
it["mail.smtp.auth"] = "true" | |
it["mail.smtp.port"] = "465" | |
} | |
val session = Session.getDefaultInstance(properties, object : Authenticator() { | |
override fun getPasswordAuthentication(): PasswordAuthentication { | |
return PasswordAuthentication(email, password) | |
} | |
}) | |
try { | |
MimeMessage(session).let { mime -> | |
mime.setFrom(InternetAddress(email)) | |
mime.addRecipient(Message.RecipientType.TO, InternetAddress(recipient)) | |
mime.subject = subject | |
mime.setText(message) | |
Transport.send(mime) | |
} | |
} catch (e: Exception) { | |
Log.d("RYCHU", "SendEmailService sendEmail() Catch ${e.message}") | |
emitter.onError(e) | |
} | |
}.subscribeOn(Schedulers.io()) | |
.subscribe({ | |
}, { | |
Log.d("RYCHU", "SendEmailService sendEmail() Error ${it.message}") | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment