2 回答
TA贡献1811条经验 获得超6个赞
String host = "smtp.xyz.com";
final String username = "xyz@business.com";
final String password = "your password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
// go to account setting -> smtp setting and get server name and port
props.put("mail.smtp.host", "your server name");
props.put("mail.smtp.port", "your server port");
props.put("mail.debug", "true");
try {
Session session = Session.getInstance(prop,
new javax.mail.Authenticator() {
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication(username, password);
}
});
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("xyz@business.com"));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("abc@business.com"));
msg.setSubject("Test E-Mail through Java");
Transport.send(msg,username,password);
System.out.println("Sent message successfully...");
}catch(Exception e){
}
你可以试试这个可能会解决你的问题!!!!
TA贡献1830条经验 获得超3个赞
此代码对我有用:-
public static void SendMessage(final String femail, final String fpass, final String email, final String subject, final String message)
{
//Creating properties
Properties props = new Properties();
//Configuring properties for gmail
//If you are not using gmail you may need to change the values
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
//Creating a new session
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
//Authenticating the password
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(femail, fpass);
}
});
try {
//Creating MimeMessage object
MimeMessage mm = new MimeMessage(session);
//Setting sender address
mm.setFrom(new InternetAddress(femail));
//Adding receiver
mm.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
//Adding subject
mm.setSubject(subject);
//Adding message
mm.setText(message);
//Sending email
Transport.send(mm);
} catch (MessagingException e) {
e.printStackTrace();
}
}
我已经编辑了代码并使用 starttls 方法进行了设置。
希望会有所帮助!!!!
添加回答
举报