最近我正在做一个Android实验,我想使用SMTP服务器通过android应用程序通过身份验证和加密来发送电子邮件。

好吧, 我发现Android上的javax.mail并不是一个很好的选择 ,因为它取决于awt类(我猜是传统); 有些人试图对其进行调整,以使您不需要整个awt软件包 ,但我在此方面收效甚微。 更不用说那些人几年前自己重构了Android的javax.mail,没有任何维护。

我想到的另一个选择是重新使用Apache Commons Net : 由于该社区向原始SMTP客户端添加了SMTPSClient和AuthenticatingSMTPClient ( 并为SSL和身份验证应用了我的一点补丁 ),因此您可以将该库嵌入Android应用程序(无需传递依赖项)以在安全层上使用身份验证发送邮件。 ( 这篇文章实际上激发了我的灵感 ,但是它使用的是Apache Commons Net的旧版本,而使用3.3则不再需要这样做)

SMTP身份验证和具有Commons Net的STARTTLS

通常,用于此问题的端口是25或备用587端口:您通过普通连接连接到SMTP服务器,要求提供可用的命令,如果支持STARTTLS,则使用它,其余的通信将被加密。

让我们以gmail为例,因为smtp.gmail.com支持身份验证和STARTTLS

public void sendEmail() throws Exception {  String hostname = "smtp.gmail.com";int port = 587;String password = "gmailpassword";String login = "account@gmail.com";String from = login;String subject = "subject" ;String text = "message";AuthenticatingSMTPClient client = new AuthenticatingSMTPClient();try {String to = "recipient@email.com";// optionally set a timeout to have a faster feedback on errorsclient.setDefaultTimeout(10 * 1000);// you connect to the SMTP serverclient.connect(hostname, port);// you say ehlo  and you specify the host you are connecting from, could be anythingclient.ehlo("localhost");// if your host accepts STARTTLS, we're good everything will be encrypted, otherwise we're done hereif (client.execTLS()) {client.auth(AuthenticatingSMTPClient.AUTH_METHOD.LOGIN, login, password);checkReply(client);client.setSender(from);checkReply(client);client.addRecipient(to);checkReply(client);Writer writer = client.sendMessageData();if (writer != null) {SimpleSMTPHeader header = new SimpleSMTPHeader(from, to, subject);writer.write(header.toString());writer.write(text);writer.close();if(!client.completePendingCommand()) {// failurethrow new Exception("Failure to send the email "+ client.getReply() + client.getReplyString());}} else {throw new Exception("Failure to send the email "+ client.getReply() + client.getReplyString());}} else {throw new Exception("STARTTLS was not accepted "+ client.getReply() + client.getReplyString());}} catch (Exception e) {throw e;} finally {client.logout();client.disconnect();}}private static void checkReply(SMTPClient sc) throws Exception {if (SMTPReply.isNegativeTransient(sc.getReplyCode())) {throw new Exception("Transient SMTP error " + sc.getReply() + sc.getReplyString());} else if (SMTPReply.isNegativePermanent(sc.getReplyCode())) {throw new Exception("Permanent SMTP error " + sc.getReply() + sc.getReplyString());}

这里没有什么可添加的,当然,如果您使用自己的异常类,则可以优化异常处理。

带有Commons Net的SMTP身份验证和SSL

某些SMTP服务器配置为仅接受“ a到z SSL”:您必须在向服务器发出任何命令之前确保通信的安全; 通常使用的端口是465。

让我们以LaPoste.net示例(法语帖子提供的免费电子邮件帐户)为例:

public void sendEmail() throws Exception {  String hostname = "smtp.laposte.net";int port = 465;String password = "password";String login = "firstname.lastname";String from = login + "@laposte.net";String subject = "subject" ;String text = "message";// this is the important part : you tell your client to connect using SSL right awayAuthenticatingSMTPClient client = new AuthenticatingSMTPClient("TLS",true);try {String to = "anthony.dahanne@gmail.com";// optionally set a timeout to have a faster feedback on errorsclient.setDefaultTimeout(10 * 1000);client.connect(hostname, port);client.ehlo("localhost");client.auth(AuthenticatingSMTPClient.AUTH_METHOD.LOGIN, login, password);checkReply(client);client.setSender(from);checkReply(client);client.addRecipient(to);checkReply(client);Writer writer = client.sendMessageData();if (writer != null) {SimpleSMTPHeader header = new SimpleSMTPHeader(from, to, subject);writer.write(header.toString());writer.write(text);writer.close();if(!client.completePendingCommand()) {// failurethrow new Exception("Failure to send the email "+ client.getReply() + client.getReplyString());}} else {throw new Exception("Failure to send the email "+ client.getReply() + client.getReplyString());}} catch (Exception e) {throw e;} finally {client.logout();client.disconnect();}

我在这里没有重复checkReply()方法,因为两个代码段都相同。 您会注意到,立即使用SSL意味着您不必检查execTls()响应(实际上,如果这样做,它将无法正常工作)。

包起来

就是这样 如果要使这些示例在您的环境中工作,则可以将apache commons net 3.3 jar添加到您的类路径中

如果您使用的是Maven,请添加依赖项:

<dependency><groupid>commons-net</groupid><artifactid>commons-net</artifactid><version>3.3</version>
</dependency>

如果您将Gradle用于Android项目,则还可以使用以下build.gradle文件:

buildscript {repositories {mavenCentral()}dependencies {classpath 'com.android.tools.build:gradle:0.4.2'}
}
apply plugin: 'android'repositories {mavenCentral()
}dependencies {compile fileTree(dir: 'libs', include: '*.jar'), 'commons-net:commons-net:3.3'
}android {compileSdkVersion 17buildToolsVersion "17.0.0"sourceSets {main {manifest.srcFile 'AndroidManifest.xml'java.srcDirs = ['src']resources.srcDirs = ['src']aidl.srcDirs = ['src']renderscript.srcDirs = ['src']res.srcDirs = ['res']assets.srcDirs = ['assets']}instrumentTest.setRoot('tests')}
}

请享用 !

参考:使用Anthony Dahanne博客博客中的JCG合作伙伴 Anthony Dahanne 用Apache Commons Net SMTP用Java(和Android)发送邮件:STARTTLS,SSL 。

翻译自: https://www.javacodegeeks.com/2013/11/sending-a-mail-in-java-and-android-with-apache-commons-net-smtp-starttls-ssl.html

使用Apache Commons Net SMTP以Java(和Android)发送邮件:STARTTLS,SSL相关推荐

  1. java与android https,Java-Android SSL https发布

    我在这里看到了很多类似的问题,但是找不到解决方案. 我有一个托管在x10 Premium上的Webservice PHP文件.我从他们那里购买了SSL证书,并且可以在浏览器和iPhone应用程序上通过 ...

  2. Java命令行界面(第1部分):Apache Commons CLI

    尽管我通常使用Groovy编写要从命令行运行的JVM托管脚本,但是有时候我需要解析Java应用程序中的命令行参数,并且有很多库可供Java开发人员用来解析命令行参数. 在本文中,我将介绍这些Java命 ...

  3. java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory 解决方案

    java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory 解决方案 NoClassDefFoundErrorLogFa ...

  4. java.lang.ClassNotFoundException: org.apache.commons.fileupload.disk.DiskFileItemFactory

    您好,我是码农飞哥,感谢您阅读本文!本文主要介绍文件上传报的错 问题复现 [dispatcherServlet] in context with path [/coep-rest] threw exc ...

  5. Apache工具库——Apache Commons的使用

    Apache Commons是Apache开源的一个java组件库,其中包含了大量子项目,其中常用的组件有: 组件 功能介绍 BeanUtils 提供了对于JavaBean进行各种操作,克隆对象,属性 ...

  6. Apache Commons 工具类介绍及简单使用(转)

    转自:http://www.cnblogs.com/younggun/p/3247261.html Apache Commons包含了很多开源的工具,用于解决平时编程经常会遇到的问题,减少重复劳动.下 ...

  7. Apache Commons 工具类介绍及简单使用

    Apache Commons包含了很多开源的工具,用于解决平时编程经常会遇到的问题,减少重复劳动.下面是我这几年做开发过程中自己用过的工具类做简单介绍. 组件 功能介绍 BeanUtils 提供了对于 ...

  8. 异常记录与处理-Cannot find class [org.apache.commons.dbcp.BasicDataSource]

    异常描述 在利用spring获取jdbc连接时发生如下异常,经分析可锁定为找不到org.apache.commons.dbcp.BasicDataSource(红色字体) org.springfram ...

  9. Apache Commons DbUtils 入门

    一.概述 DbUtils小巧的Java数据库操作工具,它在JDBC的基础上做了科学的封装,旨在简化JDBC代码混乱与重复. 对于JDBC代码,存在很多问题,算是对Java的批判: 1.操作过程复杂,代 ...

最新文章

  1. Android开发笔记1.2
  2. 初步了解qemu虚拟机
  3. Flink on Zeppelin 系列之:Yarn Application 模式支持
  4. 智慧城市建设面临“三座大山” 安全与服务需两手抓
  5. 408考研数据结构复习-时间复杂度与空间复杂度-附统考真题
  6. python爬虫 asyncio aiohttp aiofiles 单线程多任务异步协程爬取图片
  7. 洛谷 P1509 找啊找啊找GF(复习二维费用背包)
  8. 新传要不要学计算机,传媒计算机实在性:真实性表象和新传媒
  9. dsolve函数的功能_为什么Mathematica的DSolve函数会解不出显式解??
  10. 计算机数字信号和模拟信号,模拟信号和数字信号有什么区别
  11. Java主要应用于哪些方面 Java就业方向有哪些
  12. for循环,for...in循环,forEach循环的区别
  13. html5圆圈,圆形按钮HTML5/CSS3 button代码
  14. inet_addr,inet_pton,inet_aton 用法
  15. linux下vimrc和.vimrc以及.vimrc的常用设置
  16. heritrix参考文献
  17. html table 好看样式,好看的Table CSS 样式表
  18. I/O中read及write各个方法区别
  19. FastApi路径参数Query参数及参数类型
  20. 西门子828D数控系统主轴参数(不带编码器,只输出电压信号)

热门文章

  1. 拉取git的分支项目
  2. HashMap的实现原理及其特点
  3. vue插槽面试题_VUE面试题解析,半年出一篇,建议收藏!
  4. 转:Kafka、RabbitMQ、RocketMQ等消息中间件的介绍和对比
  5. apache isis_使用Apache Isis快速进行SEMAT应用程序开发
  6. activiti异步执行_对基于消息队列的Activiti异步执行器进行基准测试
  7. web ua检测_UA Web挑战会议:针对初创公司的SpringIO
  8. git hok json_从战中反弹:将Git提交信息作为JSON返回
  9. hibernate jpa_JPA /Hibernate刷新策略初学者指南
  10. JDK 14:CMS GC是OBE