我正在做类似的事情,但从本地主机发送。这可能会有所帮助。
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.mail.Transport;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
public class SendEmail {
/**
* Sends an email based on paramaters passed to it.
*
* @param toWho - the recipiants email address
* @param fromWho - the senders email address
* @param subject - the subject line of the email
* @param body - the email message body
* @return void
* @throws AddressException
* @throws MessageingException
*/
public void sendMail(String toWho, String subject, String body, String fromWho) throws AddressException, MessagingException {
// Setting Properties
Properties props = System.getProperties();
props.put("mail.imaps.ssl.trust", "*"); // trusting all server certificates
props.setProperty("mail.store.protocol", "imaps");
// Get the default Session object.
Session session = Session.getDefaultInstance(props, null);
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From header
message.setFrom(new InternetAddress(fromWho));
// Set to header
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toWho));
// Header set subject
message.setSubject(subject);
// Message Body
message.setContent(body, "text/html; charset=utf-8");
// Send message
Transport.send(message);
}
}