我正在使用Java Mail Api发送邮件,它在我的计算机系统上运行良好。但它不适用于客户端网络..我得到Java Messaging异常无法连接到
这是代码的snipet
private static void sendmail(String file) throws IOException
{
try {
final String username ="username";
final String password= "password";
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.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
Message message= new MimeMessage(session);
String To= "a@client.com";
String subject= "ERROR LOG IN EXCEL";
String body= "Testing Attached within";
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(To));
message.setSubject(subject);
message.setText(body);
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("eror log.xls");
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
JOptionPane.showMessageDialog(null, "message sent");
}
我得到的错误Java消息传递异常不能mail.smtp。 host smtp.gmail.com port:465
然而,这适用于我自己的系统。并且电子邮件已成功发送。
这可能是客户端网络系统的安全配置问题
答案 0 :(得分:0)
试试这个:
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendEmail
{
public static void main(String [] args)
{
// Recipient's email ID needs to be mentioned.
String to = "abcd@gmail.com";
// Sender's email ID needs to be mentioned
String from = "web@gmail.com";
// Assuming you are sending email from localhost
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}