这里我提供了一些对我有效的更改:
Session session = Session.getInstance(props,null)
您可以像之前一样实例化消息对象。最后,执行以下操作:
Transport transport = session.getTransport("smtp");
String mfrom = "yourGmailUsernameWithout@"
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);
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"));
try {
InternetAddress from = new InternetAddress("username");
message.setSubject("Yes we can");
message.setFrom(from);
message.addRecipients(Message.RecipientType.TO, InternetAddress.parse("receivermail"));
Multipart multipart = new MimeMultipart("alternative");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("some text to send");
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
String htmlMessage = "Our html text";
messageBodyPart.setContent(htmlMessage, "text/html");
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
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) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
MessagingException
后添加catch (Exception e){}
,以查看是否抛出了其他类型的异常。还应该添加一个finally
块。您还可以添加log4j.xml
并将javax.mail
类设置为DEBUG
,以查看可能发生的其他情况。 - Bizmarck