我完成了向最终用户发送邮件。但是当我在那时使用gmail帐户时我必须将smtp.domain.com更改为smtp.gmail.com,如果我从yahoomail.com发送邮件,那么我必须将smtp.gmail.com更改为smtp.mail。 yahoo.com。所以在java中有任何解决方案来发送来自任何域用户的邮件,意味着我想让我的代码通用。所以任何人都有解决方案然后请向我建议。我的代码在下面
enter code here
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 SendMailSSL {
public static void main(String[] args) {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xyz.123@gmail.com", "123456");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("xyz.123@gmail.com"));
message.setRecipient(Message.RecipientType.TO,
new InternetAddress("abc.456@gmail.com"));
message.setSubject("mail to user");
message.setText("Hello world.....");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
答案 0 :(得分:1)
使用java Properties API。 http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html 使用loadfromXML选项可以使用配置文件并使属性可配置。
或者,您可以将配置文件作为命令行参数传递,并使其可配置。
或从数据库中读取。
解决此问题的方法很多。
答案 1 :(得分:1)
从命令行运行此程序....
>java SendMailSSL <Put desire mail server as argument eg smtp.domail.com>
从您的程序中访问此命令行参数....
public static void main(String[] args) {
Properties props = new Properties();
props.put("mail.smtp.host", args[0]);