在这里我给一些变化,这些工作对我罚款:
Session session = Session.getInstance(props,null);
您实例化的消息对象为你做。最后:
Transport transport = session.getTransport("smtp");
String mfrom = "[email protected]"// example laabidiraissi
transport.connect("smtp.gmail.com", mfrom, "thepassword");
transport.sendMessage(message, message.getAllRecipients());
编辑,请你给我一个忙,复制/粘贴和尝试这个例子,显示它显示:
我可以重现行为在你的问题中描述
package com.test;
import java.util.Properties;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.junit.Test;
public class EmailService {
@Test
public void test(){
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", true); // added this line
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.user", "username");
props.put("mail.smtp.password", "password");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", true);
Session session = Session.getInstance(props,null);
MimeMessage message = new MimeMessage(session);
System.out.println("Port: "+session.getProperty("mail.smtp.port"));
// Create the email addresses involved
try {
InternetAddress from = new InternetAddress("username");
message.setSubject("Yes we can");
message.setFrom(from);
message.addRecipients(Message.RecipientType.TO, InternetAddress.parse("receivermail"));
// Create a multi-part to combine the parts
Multipart multipart = new MimeMultipart("alternative");
// Create your text message part
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("some text to send");
// Add the text part to the multipart
multipart.addBodyPart(messageBodyPart);
// Create the html part
messageBodyPart = new MimeBodyPart();
String htmlMessage = "Our html text";
messageBodyPart.setContent(htmlMessage, "text/html");
// Add html part to multi part
multipart.addBodyPart(messageBodyPart);
// Associate multi-part with message
message.setContent(multipart);
// Send message
Transport transport = session.getTransport("smtp");
transport.connect("smtp.gmail.com", "username", "password");
System.out.println("Transport: "+transport.toString());
transport.sendMessage(message, message.getAllRecipients());
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我建议在MessagingException之后添加一个'catch(Exception e){}'来查看是否有其他类型的异常被抛出。还要添加一个'finally'块。您还可以添加'log4j.xml'并将'javax.mail'类设置为'DEBUG'来查看还有什么可以进行。 – Bizmarck 2013-03-24 11:04:17
好的提示,谢谢!将测试它 – czupe 2013-03-24 11:06:39
不幸的是仍然在Transport.send(消息)行等待...有人可以验证此代码的正确性? – czupe 2013-03-24 11:28:18