根据实际情况,会用到根据第三方为我们提供邮件,短信功能。代码如下:
第三方邮箱地址网址:http://sendcloud.sohu.com/
(1)邮箱
package com.chengjun.test;
import java.io.File;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message.RecipientType;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import com.sun.mail.smtp.SMTPTransport;
public class SendEmail {
private static final String SENDCLOUD_SMTP_HOST = "smtp.sendcloud.net";
private static final int SENDCLOUD_SMTP_PORT = 25;
private static String getMessage(String reply) {
String[] arr = reply.split("#");
String messageId = null;
if (arr[0].equalsIgnoreCase("250 ")) {
messageId = arr[1];
}
return messageId;
}
public static void main(String[] args) throws Exception {
// 配置javamail
Properties props = System.getProperties();
props.setProperty("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", SENDCLOUD_SMTP_HOST);
props.put("mail.smtp.port", SENDCLOUD_SMTP_PORT);
props.setProperty("mail.smtp.auth", "true");
props.put("mail.smtp.connectiontimeout", 180);
props.put("mail.smtp.timeout", 600);
props.setProperty("mail.mime.encodefilename", "true");
// 使用api_user和api_key进行验证
final String apiUser = "chengjun202_test_M2V5UR";
final String apiKey = "ebLQ1y9W4XIVDNT7";
Session mailSession = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(apiUser, apiKey);
}
});
SMTPTransport transport = (SMTPTransport) mailSession.getTransport("smtp");
MimeMessage message = new MimeMessage(mailSession);
// 发信人
message.setFrom(new InternetAddress("from@sendcloud.org", "发件人名称", "UTF-8"));
// 收件人地址
message.addRecipient(RecipientType.TO, new InternetAddress("收件人地址"));
// 邮件主题
message.setSubject("邮件主题", "UTF-8");
Multipart multipart = new MimeMultipart("alternative");
// 添加html形式的邮件正文
//<html><head></head><body>" + "<p>欢迎使用<a href='http://sendcloud.sohu.com'>SendCloud!</a></p>" + "</body></html>可以任意修改,根据html基本原则;
String html = "<html><head></head><body>" + "<p>欢迎使用<a href='http://sendcloud.sohu.com'>SendCloud!</a></p>" + "</body></html> ";
BodyPart contentPart = new MimeBodyPart();
contentPart.setHeader("Content-Type", "text/html;charset=UTF-8");
contentPart.setHeader("Content-Transfer-Encoding", "base64");
contentPart.setContent(html, "text/html;charset=UTF-8");
multipart.addBodyPart(contentPart);
// 添加附件 ( smtp 方式没法使用文件流 )
File file = new File("E:/server.xml");
BodyPart attachmentBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(file);
attachmentBodyPart.setDataHandler(new DataHandler(source));
attachmentBodyPart.setFileName(MimeUtility.encodeWord(file.getName()));
multipart.addBodyPart(attachmentBodyPart);
message.setContent(multipart);
// 连接sendcloud服务器,发送邮件
transport.connect();
transport.sendMessage(message, message.getRecipients(RecipientType.TO));
String messageId = getMessage(transport.getLastServerResponse());
String emailId = messageId + "0$" + "收件人地址";
System.out.println("messageId:" + messageId);
System.out.println("emailId:" + emailId);
transport.close();
}
}
需要用到的jar包;
![这里写代码片](https://img-blog.csdn.net/20170421172830045?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcXFfMzUzMzM4NDM=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
(2)短信
package com.chengjun.test;
/**
*短信
*/
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
public class SendMessage {
private static String Url = “http://106.ihuyi.cn/webservice/sms.php?method=Submit“;
public static void main(String[] args) {
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(Url);
client.getParams().setContentCharset("UTF-8");
method.setRequestHeader("ContentType",
"application/x-www-form-urlencoded;charset=UTF-8");
int mobile_code = (int) ((Math.random() * 9 + 1) * 100000);
String content = new String("您的验证码是:" + mobile_code + "。请不要把验证码泄露给其他人。");
NameValuePair[] data = {// 提交短信
new NameValuePair("account", "用户名"), // 查看用户名请登录用户中心->验证码、通知短信->帐户及签名设置->APIID
new NameValuePair("password", "密码"), // 查看密码请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY
new NameValuePair("mobile", "手机号码"),
new NameValuePair("content", content), };
method.setRequestBody(data);
try {
client.executeMethod(method);
String SubmitResult = method.getResponseBodyAsString();
Document doc = DocumentHelper.parseText(SubmitResult);
Element root = doc.getRootElement();
String code = root.elementText("code");
String msg = root.elementText("msg");
String smsid = root.elementText("smsid");
System.out.println(code);
System.out.println(msg);
System.out.println(smsid);
if ("2".equals(code)) {
System.out.println("短信提交成功");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}