下面列出了javax.mail.Session#getInstance ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private Session getSession() {
if(session == null) {
final String fromEmail = environment.getProperty("from.email");
final String password = environment.getProperty("email.password");
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Authenticator auth = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
};
this.session = Session.getInstance(props, auth);
}
return session;
}
/**
* Get the connection to a mail store
*
* @param user whose mail store should be connected
* @param protocol protocol used to connect
* @return
* @throws MessagingException when unable to connect to the store
*/
private static Store getConnection(GreenMailUser user, String protocol) throws MessagingException {
Properties props = new Properties();
Session session = Session.getInstance(props);
int port;
if (PROTOCOL_POP3.equals(protocol)) {
port = 3110;
} else if (PROTOCOL_IMAP.equals(protocol)) {
port = 3143;
} else {
port = 3025;
props.put("mail.smtp.auth", "true");
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", "localhost");
props.put("mail.smtp.port", "3025");
}
URLName urlName = new URLName(protocol, BIND_ADDRESS, port, null, user.getLogin(), user.getPassword());
Store store = session.getStore(urlName);
store.connect();
return store;
}
/** */
@Override
protected void setUp() throws Exception
{
super.setUp();
Properties props = new Properties();
props.setProperty("mail.smtp.host", "localhost");
props.setProperty("mail.smtp.port", Integer.toString(PORT));
this.session = Session.getInstance(props);
this.wiser = new Wiser();
this.wiser.setPort(PORT);
this.wiser.start();
}
@Test
public void checkSmtpServer() throws Exception {
Properties props = new Properties();
props.setProperty("mail.smtp.host", TEST_SMTP_HOST);
props.setProperty("mail.smtp.port", String.valueOf(TEST_SMTP_PORT));
Session session = Session.getInstance(props);
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("[email protected]"));
message.setSubject("Check SMTP Server");
message.setText("This is the text of the message");
Transport.send(message);
assertEquals(1, server.getReceivedMessages().length);
}
public void sendMail(String receiver, String subject, String message) throws Exception
{
Properties properties = new Properties();
properties.setProperty("mail.transport.protocol", "smtp");//发送邮件协议
properties.setProperty("mail.smtp.auth", "true");//需要验证
Session session = Session.getInstance(properties);
session.setDebug(false);
//邮件信息
Message messgae = new MimeMessage(session);
messgae.setFrom(new InternetAddress(getMailFrom()));//设置发送人
messgae.setText(message);//设置邮件内容
messgae.setSubject(subject);//设置邮件主题
//发送邮件
Transport tran = session.getTransport();
tran.connect(getServerHost(), getServerPort(), getAuthUserName(), getAuthPassword());
tran.sendMessage(messgae, new Address[] { new InternetAddress(receiver) });//设置邮件接收人
tran.close();
Logger.getLogger(this.getClass()).debug(String.format("sent mail to <%s>: %s", receiver, subject));
}
public void init()
{
if (_toList.size() == 0)
throw new ConfigException(L.l("mail service requires at least one 'to' address"));
_to = new Address[_toList.size()];
_toList.toArray(_to);
_from = new Address[_fromList.size()];
_fromList.toArray(_from);
try {
if (_session == null) {
_session = Session.getInstance(_properties);
}
Transport smtp = _session.getTransport("smtp");
smtp.close();
} catch (Exception e) {
throw ConfigException.wrap(e);
}
}
public JavaMail(boolean debug) {
// InputStream in = JavaMail.class.getResourceAsStream("MailServer.properties");
// properties.load(in);
// this.host = "smtp.qq.com";
this.host = "smtp.gmail.com";
this.port=587;
// this.sender_username = "[email protected]";
// this.sender_password ="cxksiyvwxerubicf";
this.sender_username = "[email protected]";
this.sender_password ="";
// Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
// properties.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketF");
properties.put("mail.smtp.socketFactory.fallback", "false");
properties.put("mail.smtp.starttls.enable", "true");
session = Session.getInstance(properties);
session.setDebug(debug);//开启后有调试信息
message = new MimeMessage(session);
}
public static Boolean connect(Properties props)
throws MessagingException, IOException {
Properties properties = decryptValues(props);
Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
properties.getProperty("username"),
properties.getProperty("password"));
}
});
Transport transport = session.getTransport("smtp");
transport.connect();
transport.close();
return true;
}
/**
* send email
*
* @throws MessagingException
* @throws Exception
*/
public static int sendMail(String subject, String content, String mails,
String cc) throws MessagingException {
Properties props = new Properties();
props.put("mail.smtp.host", HOST);
props.put("mail.smtp.starttls.enable", "true");
// props.put("mail.smtp.port", "25");
props.put("mail.smtp.auth", "true");
// props.put("mail.debug", "true");
Session mailSession = Session.getInstance(props, new MyAuthenticator());
Message message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(FROM));
message.addRecipients(Message.RecipientType.TO, getMailList(mails));
message.addRecipients(Message.RecipientType.CC, getMailList(cc));
message.setSubject(subject);
message.setContent(content, "text/html;charset=utf-8");
Transport transport = mailSession.getTransport("smtp");
try {
transport.connect(HOST, USER, PASSWORD);
transport.sendMessage(message, message.getAllRecipients());
} finally {
if (transport != null)
transport.close();
}
return 0;
}
private boolean sendMail(boolean isResolve, ClusterAlertBean clusterAlertBean) {
try {
Properties props = new Properties();
// 开启debug调试
props.setProperty("mail.debug", "true");
// 发送服务器需要身份验证
props.setProperty("mail.smtp.auth", "true");
// 设置邮件服务器主机名
props.setProperty("mail.host", properties.getProperty(MAIL_SERVER));
// 发送邮件协议名称
props.setProperty("mail.transport.protocol", "smtp");
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sf);
Session session = Session.getInstance(props);
Message msg = new MimeMessage(session);
msg.setSubject("DBLE告警 " + (isResolve ? "RESOLVE\n" : "ALERT\n"));
StringBuilder builder = new StringBuilder();
builder.append(groupMailMsg(clusterAlertBean, isResolve));
msg.setText(builder.toString());
msg.setFrom(new InternetAddress(properties.getProperty(MAIL_SENDER)));
Transport transport = session.getTransport();
transport.connect(properties.getProperty(MAIL_SERVER), properties.getProperty(MAIL_SENDER), properties.getProperty(SENDER_PASSWORD));
transport.sendMessage(msg, new Address[]{new InternetAddress(properties.getProperty(MAIL_RECEIVE))});
transport.close();
//send EMAIL SUCCESS return TRUE
return true;
} catch (Exception e) {
e.printStackTrace();
}
//send fail reutrn false
return false;
}
@Test
public void javaMailSenderWithCustomSession() throws MessagingException {
final Session session = Session.getInstance(new Properties());
MockJavaMailSender sender = new MockJavaMailSender() {
@Override
protected Transport getTransport(Session sess) throws NoSuchProviderException {
assertEquals(session, sess);
return super.getTransport(sess);
}
};
sender.setSession(session);
sender.setHost("host");
sender.setUsername("username");
sender.setPassword("password");
MimeMessage mimeMessage = sender.createMimeMessage();
mimeMessage.setSubject("custom");
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
mimeMessage.setSentDate(new GregorianCalendar(2005, 3, 1).getTime());
sender.send(mimeMessage);
assertEquals("host", sender.transport.getConnectedHost());
assertEquals("username", sender.transport.getConnectedUsername());
assertEquals("password", sender.transport.getConnectedPassword());
assertTrue(sender.transport.isCloseCalled());
assertEquals(1, sender.transport.getSentMessages().size());
assertEquals(mimeMessage, sender.transport.getSentMessage(0));
}
public TestMailClient(int port, String smtpHost) {
Properties props = new Properties();
props.put("mail.smtp.auth", "false");
props.put("mail.smtp.starttls.enable", "false");
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.port", port);
session = Session.getInstance(props);
}
/**
* Return the JavaMail {@code Session},
* lazily initializing it if hasn't been specified explicitly.
*/
public synchronized Session getSession() {
if (this.session == null) {
this.session = Session.getInstance(this.javaMailProperties);
}
return this.session;
}
@Override
public void sendHtmlMail(String to, String title, String content) {
EmailSetting emailSetting = configService.selectConfigByConfigKey(ConfigKey.CONFIG_KEY_EMAIL_SETTING, EmailSetting.class);
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setUsername(emailSetting.getUser());
mailSender.setHost(emailSetting.getHost());
mailSender.setDefaultEncoding("utf-8");
mailSender.setPassword(emailSetting.getPassword());
mailSender.setPort(emailSetting.getPort());
Properties properties = new Properties();
properties.put("mail.smtp.host", emailSetting.getHost());
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.socketFactory.fallback", "false"); // 只处理SSL的连接,对于非SSL的连接不做处理
properties.put("mail.smtp.port", emailSetting.getPort());
properties.put("mail.smtp.socketFactory.port", emailSetting.getPort());
properties.put("mail.smtp.ssl.enable", true);
Session session = Session.getInstance(properties);
MimeMessage mimeMessage = mailSender.createMimeMessage();
try {
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
mimeMessageHelper.setFrom(emailSetting.getFromEmail());
mimeMessageHelper.setTo(to);
if (StringUtils.isNotEmpty(emailSetting.getStationmasterEmail())) {
mimeMessageHelper.setBcc(emailSetting.getStationmasterEmail());
}
mimeMessageHelper.setSubject(title);
mimeMessageHelper.setText(content, true);
mailSender.setSession(session);
mailSender.send(mimeMessage);
} catch (MessagingException e) {
log.error(e.getMessage(), e);
}
}
private Session createSession() {
Properties p = new Properties();
if (mock()) {
p.setProperty("mail.smtp.host", "unknown");
p.setProperty("mail.smtp.port", "465");
} else {
p.setProperty("mail.smtp.host", host);
p.setProperty("mail.smtp.port", port);
}
if (null != username && null != password) {
if (useTls) {
p.put("mail.smtp.starttls.enable", "true");
} else if (useSsl) {
p.put("mail.smtp.socketFactory.port", port);
p.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
}
p.setProperty("mail.smtp.auth", "true");
Authenticator auth = new Authenticator() {
//override the getPasswordAuthentication method
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
};
return Session.getInstance(p, auth);
} else {
return Session.getInstance(p);
}
}
/**
* 发送邮件
* @param title 邮件标题
* @param body 邮件正文
*/
public static void sendMaid(String title, String body){
PropertiesUtil pro = new PropertiesUtil();
Properties props = new Properties();
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.ssl.enable", "true");
props.setProperty("mail.smtp.connectiontimeout", "5000");
try{
//1、创建session
Session session = Session.getInstance(props);
//开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
//session.setDebug(true);
//2、通过session得到transport对象
Transport ts = session.getTransport("smtp");
//3、使用邮箱的用户名和密码连上邮件服务器,
ts.connect(pro.getProperty("SERVER_HOST"), Integer.parseInt(pro.getProperty("SERVER_PORT")), pro.getProperty("SEND_USER"), pro.getProperty("PASSWORD"));
//4、创建邮件
MimeMessage message = new MimeMessage(session);
//指明邮件的发件人
message.setFrom(new InternetAddress(pro.getProperty("SEND_USER")));
//指明邮件的收件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(pro.getProperty("RECEIVE_USER")));
//邮件的标题
message.setSubject(title);
//邮件的文本内容
message.setContent(body, "text/html;charset=UTF-8");
//5、发送邮件
ts.sendMessage(message, message.getAllRecipients());
ts.close();
} catch (Exception e){
e.printStackTrace();
}
}
@Override
public void start() throws Exception
{
Properties mailProps = new Properties();
mailProps.setProperty("mail.store.protocol", getProperty("mailbox_protocol"));
if ("pop3".equals(getProperty("mailbox_protocol")))
{
mailProps.setProperty("mail.pop3.host", getProperty("mailbox_host"));
mailProps.setProperty("mail.pop3.port", getProperty("mailbox_port"));
mailProps.setProperty("mail.pop3.user", getProperty("mailbox_user"));
mailProps.setProperty("mail.pop3.password", getProperty("mailbox_password"));
}
else if ("pop3s".equals(getProperty("mailbox_protocol")))
{
mailProps.setProperty("mail.pop3s.host", getProperty("mailbox_host"));
mailProps.setProperty("mail.pop3s.port", getProperty("mailbox_port"));
mailProps.setProperty("mail.pop3s.user", getProperty("mailbox_user"));
mailProps.setProperty("mail.pop3s.password", getProperty("mailbox_password"));
}
else if ("imap".equals(getProperty("mailbox_protocol")))
{
mailProps.setProperty("mail.imap.host", getProperty("mailbox_host"));
mailProps.setProperty("mail.imap.port", getProperty("mailbox_port"));
mailProps.setProperty("mail.imap.user", getProperty("mailbox_user"));
mailProps.setProperty("mail.imap.password", getProperty("mailbox_password"));
}
else if ("imaps".equals(getProperty("mailbox_protocol")))
{
mailProps.setProperty("mail.imaps.host", getProperty("mailbox_host"));
mailProps.setProperty("mail.imaps.port", getProperty("mailbox_port"));
mailProps.setProperty("mail.imaps.user", getProperty("mailbox_user"));
mailProps.setProperty("mail.imaps.password", getProperty("mailbox_password"));
}
else
{
throw new IllegalArgumentException("mailbox_protocol have to be pop3(s) or imap(s)!");
}
mailProps.setProperty("mail.transport.protocol", "smtp");
mailProps.setProperty("mail.from", getProperty("from"));
mailProps.setProperty("mail.smtp.host", getProperty("smtp_host"));
mailProps.setProperty("mail.smtp.port", getProperty("smtp_port"));
mailProps.setProperty("mail.smtp.user", getProperty("smtp_user"));
mailProps.setProperty("mail.smtp.password", getProperty("smtp_password"));
mailProps.setProperty("mail.smtp.auth", "true");
this.mailSession = Session.getInstance(mailProps, new javax.mail.Authenticator()
{
@Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(getProperty("mailbox_user"), getProperty("mailbox_password"));
}
});
if (isOutbound())
{
prepareEmailTemplate();
}
super.start();
}
private Session buildSessionFromProperties() {
Properties props = new Properties(OptionHelper.getSystemProperties());
if (smtpHost != null) {
props.put("mail.smtp.host", smtpHost);
}
props.put("mail.smtp.port", Integer.toString(smtpPort));
if (localhost != null) {
props.put("mail.smtp.localhost", localhost);
}
LoginAuthenticator loginAuthenticator = null;
if (username != null) {
loginAuthenticator = new LoginAuthenticator(username, password);
props.put("mail.smtp.auth", "true");
}
if (isSTARTTLS() && isSSL()) {
addError("Both SSL and StartTLS cannot be enabled simultaneously");
} else {
if (isSTARTTLS()) {
// see also http://jira.qos.ch/browse/LBCORE-225
props.put("mail.smtp.starttls.enable", "true");
}
if (isSSL()) {
String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
props.put("mail.smtp.socketFactory.port",
Integer.toString(smtpPort));
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
props.put("mail.smtp.socketFactory.fallback", "true");
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.transport.protocol", "smtps");
props.put("mail.smtps.ssl.trust", "*");
}
}
// props.put("mail.debug", "true");
return Session.getInstance(props, loginAuthenticator);
}
public MimeMessage getBasicMimeMessage() throws Exception {
log.debug("getBasicMimeMessage");
if (getSmtpServer() == null) {
throw new IllegalStateException("SMTP settings were not provided");
}
Properties props = new Properties(System.getProperties());
props.put("mail.smtp.host", getSmtpServer());
props.put("mail.smtp.port", getSmtpPort());
if (isSmtpUseTls() || isSmtpUseSsl()) {
props.put("mail.smtp.ssl.trust", getSmtpServer());
}
if (isSmtpUseTls() && isSmtpUseSsl()) {
log.warn("Both SSL and TLS are enabled, TLS will be started");
}
props.put("mail.smtp.starttls.enable", isSmtpUseTls());
props.put("mail.smtp.ssl.enable", isSmtpUseSsl());
props.put("mail.smtp.connectiontimeout", getSmtpConnectionTimeOut());
props.put("mail.smtp.timeout", getSmtpTimeOut());
// Check for Authentication
Session session;
if (!Strings.isEmpty(getSmtpUser()) && !Strings.isEmpty(getSmtpPass())) {
// use SMTP Authentication
props.put("mail.smtp.auth", true);
session = Session.getDefaultInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(getSmtpUser(), getSmtpPass());
}
});
} else {
// not use SMTP Authentication
session = Session.getInstance(props, null);
}
// Building MimeMessage
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(getMailFrom()));
return msg;
}
public TransportMock() {
super(Session.getInstance(new Properties()), new URLName(""));
}