在Ubuntu上配置Java邮件服务,通常使用Postfix作为邮件服务器,搭配JavaMail API实现邮件发送功能,具体步骤如下:
sudo apt update
和sudo apt install postfix
,安装过程中选择“Internet Site”配置类型,设置系统邮件名称。/etc/postfix/main.cf
文件,可设置SMTP端口、认证方式等参数,如mail.smtp.port=25
,mail.smtp.auth=true
等。sudo apt install dovecot-core dovecot-imapd dovecot-pop3d
,并配置相关文件。sudo systemctl start postfix
和sudo systemctl enable postfix
,启动Postfix服务,若安装了Dovecot,也需启动该服务。telnet localhost 25
测试SMTP服务是否正常,或使用mail
命令发送测试邮件。import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class EmailSender {
public static void main(String[] args) {
String host = "localhost";
String username = "your_username";
String password = "your_password";
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.addRecipient(Message.RecipientType.TO, new InternetAddress("recipient@example.com"));
message.setSubject("Test Email");
message.setText("This is a test email.");
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}