代码:
package maintestcases;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.*;
import java.io.*;
public class SendMailSSL {
//ClassLoader classLoader;
@Test
public void email() {
final BodyPart messageBodyPart;
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
final Properties props = new Properties();
try {
props.load(classLoader.getResourceAsStream("maintestcases/Credentials.properties"));
String Username = props.getProperty("username");
String Password= props.getProperty("password");
} catch (IOException e) {
e.printStackTrace();
}
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.***.com");
props.put("mail.smtp.port", "465");
Session session = Session.getInstance(props,new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(props.getProperty("username"),props.getProperty("password"));
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("vijayalakshmi.lakshmanan@xxxx.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("vijayalakshmi.lakshmanan@xxxx.com"));
message.setSubject("Automation Testing report");
message.setText("Dear Mail Crawler,"
+ "\n\n No spam to my email, please!");
MimeBodyPart p1 = new MimeBodyPart();
String html = "<html><head><title>" +
message.getSubject() +
"</title></head><body><h1>" +
message.getSubject() +
"</h1><p>This is a test of sending an HTML e-mail" +
" through Java.</body></html>";
p1.setDescription(html);
MimeBodyPart p2 = new MimeBodyPart();
FileDataSource fds = new FileDataSource("C:\\Documents and Settings\\vlakshm\\workspace\\Trial\\test-output\\emailable-report.html");
p2.setDataHandler(new DataHandler(fds));
p2.setFileName(fds.getName());
Multipart mp = new MimeMultipart();
mp.addBodyPart(p1);
mp.addBodyPart(p2);
message.setContent(mp);
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
属性文件中的内容:
Credentials.properities file:
username:domain/username
Password:********
执行下面提到的代码时,我收到错误
“javax.mail.AuthenticationFailedException:535 5.7.3身份验证失败。”。
虽然用户名和密码是正确的。
答案 0 :(得分:1)
当我将用户名从domain\username
更改为username
时,我收到了结果。