在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();
}
}
}