java写一个发送接口
时间: 2023-05-21 14:06:37 浏览: 79
可以使用JavaMail API来写一个发送接口,以下是一个示例代码:
```
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class EmailSender {
public void sendEmail(String toAddress, String subject, String text) {
final String username = "youremail@gmail.com";
final String password = "yourpassword"; // Note: This is your Gmail password, not your CSDN password.
String host = "smtp.gmail.com";
int port = 587;
// Set email properties
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
// Get mail session
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// Create message
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(toAddress));
message.setSubject(subject);
message.setText(text);
// Send message
Transport.send(message);
System.out.println("Email sent successfully!");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
```
调用 sendEmail 方法,像这样:
```
EmailSender sender = new EmailSender();
sender.sendEmail("recipient@example.com", "Test Subject", "This is a test email from Java.");
```
该代码将使用 Gmail SMTP 服务器与收件人收取邮箱连接并发送电子邮件。请确保使用正确的邮箱地址和密码。
阅读全文