用java写一个短信发送接口
时间: 2023-03-14 19:39:29 浏览: 57
我可以为您提供一个基于Java的短信发送接口的示例代码:import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;public class SendSMS {
public static void main(String[] args) {
// 请替换为您的短信服务商的用户名和密码
String username = "username";
String password = "password";
// 配置发件服务器
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.example.com");
props.put("mail.smtp.port", "25");
props.put("mail.smtp.auth", "true");
// 建立连接
Session session = Session.getInstance(
props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// 创建消息
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from@example.com"));
message.setRecipients(
Message.RecipientType.TO,
InternetAddress.parse("to@example.com")
);
message.setSubject("Testing Subject");
message.setText("Hello, this is a test!");
// 发送消息
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}