maven依赖
<!-- 阿里信息服务-->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.0.3</version>
</dependency>
<!-- Java邮件 -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.5</version>
</dependency>
代码
public class SmsUtil {
public static void smsServerException(String phoneNumbers, String code) {
String accessKeyId = "";
String secret = "";
DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, secret);
IAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest();
request.setMethod(MethodType.POST);
request.setDomain("dysmsapi.aliyuncs.com");
request.setVersion("2017-05-25");
request.setAction("SendSms");
request.putQueryParameter("RegionId", "cn-hangzhou");
request.putQueryParameter("PhoneNumbers", phoneNumbers);
request.putQueryParameter("SignName", "签名名称");
request.putQueryParameter("TemplateCode", "SMS_123456");
request.putQueryParameter("TemplateParam", "{\"name\":\"" + code + "\"}");
try {
CommonResponse response = client.getCommonResponse(request);
System.out.println(response.getData());
} catch (com.aliyuncs.exceptions.ClientException e) {
e.printStackTrace();
}
}
public static void sendrMail(String addresser, String secret, String recipients, String subject, String content)
throws AddressException, MessagingException {
Properties props = new Properties();
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "smtp.qq.com");
props.setProperty("mail.smtp.port", "587");
props.setProperty("mail.smtp.socketFactory.port", "465");
Session session = Session.getInstance(props,
new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(addresser, secret);
}
}
);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(addresser));
msg.setSubject(subject);
InternetAddress[] address = InternetAddress.parse(recipients);
msg.setRecipients(MimeMessage.RecipientType.TO,
address);
msg.setContent("<font color=\"red\">" + content + "</font>", "text/html;charset=gbk");
System.out.println("邮件开始发送!");
Transport.send(msg);
System.out.println("邮件发送成功!");
}
public static void main(String[] args) {
smsServerException("13636363366", "你好!世界!");
try {
sendrMail("jie@jie.com", "密钥", "jie@163.com,jie@126.com", "主题", "你好:世界");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}