由于Android自身不带javamail的jar包,仅仅为了实现一个发邮件功能而引用那么多jar包划不来,
所以通过socket通信用命令行的方式来发邮件。
一个方法即可搞定!
public static boolean sendEmail(String senderEmail, String receiverEmail, String username, String pwd,
String subject, String content) {
boolean isSend = false;
//验证参数
if (senderEmail == null || receiverEmail == null || username == null || pwd == null || subject == null
|| content == null) {
throw new NullPointerException("params can not be null!...........");
}
//验证邮箱
Pattern pattern = Pattern.compile("[//w//.//-]+@([//w//-]+//.)+[//w//-]+", Pattern.CASE_INSENSITIVE);
if (!Utility.RegexMatcher(senderEmail, pattern) || !Utility.RegexMatcher(receiverEmail, pattern)) {
throw new IllegalArgumentException("email format error!.............");
}
Socket sc = null;
InputStream is = null;
OutputStream os = null;
String smtpServer = "smtp." + senderEmail.substring(senderEmail.indexOf("@") + 1, senderEmail.length());// 邮件服务器地址
final String END_TAG = "/r/n";
StringBuffer request = new StringBuffer();
StringBuffer response = new StringBuffer();
Constants.log("smtpServer:" + smtpServer);
try {
sc = new Socket(InetAddress.getByName(smtpServer), 25);
sc.setSoTimeout(30000);//设置超时
is = sc.getInputStream();
os = sc.getOutputStream();
response = response.replace(0, response.length(), transStreamToString(is, 4096));//读取服务器返回数据
Constants.log("<<<" + response);//打印log
if (response.indexOf("220") >= 0) {// 连接smtp服务器成功!
// 打招呼
request.replace(0, request.length(), "ehlo ")
.append(senderEmail.substring(0, senderEmail.indexOf("@"))).append(END_TAG);//发送命令到服务器
Constants.log(">>>" + request);
os.write(request.toString().getBytes());
response = response.replace(0, response.length(), transStreamToString(is, 4096));
Constants.log("<<<" + response);
if (response.indexOf(&#