当前位置: 首页>>代码示例>>Java>>正文


Java SMTPTransport类代码示例

本文整理汇总了Java中com.sun.mail.smtp.SMTPTransport的典型用法代码示例。如果您正苦于以下问题:Java SMTPTransport类的具体用法?Java SMTPTransport怎么用?Java SMTPTransport使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


SMTPTransport类属于com.sun.mail.smtp包,在下文中一共展示了SMTPTransport类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: send

import com.sun.mail.smtp.SMTPTransport; //导入依赖的package包/类
@Override
public void send(String senderAddress, String senderName, String recipient, String content) {
    if (StringUtils.isBlank(senderAddress)) {
        throw new FeatureNotAvailable("3PID Email identity: sender address is empty - " +
                "You must set a value for notifications to work");
    }

    if (StringUtils.isBlank(content)) {
        throw new InternalServerError("Notification content is empty");
    }

    try {
        InternetAddress sender = new InternetAddress(senderAddress, senderName);
        MimeMessage msg = new MimeMessage(session, IOUtils.toInputStream(content, StandardCharsets.UTF_8));
        msg.setHeader("X-Mailer", "mxisd"); // FIXME set version
        msg.setSentDate(new Date());
        msg.setFrom(sender);
        msg.setRecipients(Message.RecipientType.TO, recipient);
        msg.saveChanges();

        log.info("Sending invite to {} via SMTP using {}:{}", recipient, cfg.getHost(), cfg.getPort());
        SMTPTransport transport = (SMTPTransport) session.getTransport("smtp");
        transport.setStartTLS(cfg.getTls() > 0);
        transport.setRequireStartTLS(cfg.getTls() > 1);

        log.info("Connecting to {}:{}", cfg.getHost(), cfg.getPort());
        transport.connect(cfg.getHost(), cfg.getPort(), cfg.getLogin(), cfg.getPassword());
        try {
            transport.sendMessage(msg, InternetAddress.parse(recipient));
            log.info("Invite to {} was sent", recipient);
        } finally {
            transport.close();
        }
    } catch (UnsupportedEncodingException | MessagingException e) {
        throw new RuntimeException("Unable to send e-mail invite to " + recipient, e);
    }
}
 
开发者ID:kamax-io,项目名称:mxisd,代码行数:38,代码来源:EmailSmtpConnector.java

示例2: sendEmail

import com.sun.mail.smtp.SMTPTransport; //导入依赖的package包/类
public void sendEmail() throws MessagingException {
  checkSettings();
  Properties props = new Properties();
  if (_usesAuth) {
    props.put("mail." + protocol + ".auth", "true");
    props.put("mail.user", _mailUser);
    props.put("mail.password", _mailPassword);
  } else {
    props.put("mail." + protocol + ".auth", "false");
  }
  props.put("mail." + protocol + ".host", _mailHost);
  props.put("mail." + protocol + ".timeout", _mailTimeout);
  props.put("mail." + protocol + ".connectiontimeout", _connectionTimeout);
  props.put("mail.smtp.starttls.enable", _tls);
  props.put("mail.smtp.ssl.trust", _mailHost);

  Session session = Session.getInstance(props, null);
  Message message = new MimeMessage(session);
  InternetAddress from = new InternetAddress(_fromAddress, false);
  message.setFrom(from);
  for (String toAddr : _toAddress)
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(
        toAddr, false));
  message.setSubject(_subject);
  message.setSentDate(new Date());

  if (_attachments.size() > 0) {
    MimeMultipart multipart =
        this._enableAttachementEmbedment ? new MimeMultipart("related")
            : new MimeMultipart();

    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setContent(_body.toString(), _mimeType);
    multipart.addBodyPart(messageBodyPart);

    // Add attachments
    for (BodyPart part : _attachments) {
      multipart.addBodyPart(part);
    }

    message.setContent(multipart);
  } else {
    message.setContent(_body.toString(), _mimeType);
  }

  // Transport transport = session.getTransport();

  SMTPTransport t = (SMTPTransport) session.getTransport(protocol);

  try {
    connectToSMTPServer(t);
  } catch (MessagingException ste) {
    if (ste.getCause() instanceof SocketTimeoutException) {
      try {
        // retry on SocketTimeoutException
        connectToSMTPServer(t);
        logger.info("Email retry on SocketTimeoutException succeeded");
      } catch (MessagingException me) {
        logger.error("Email retry on SocketTimeoutException failed", me);
        throw me;
      }
    } else {
      logger.error("Encountered issue while connecting to email server", ste);
      throw ste;
    }
  }
  t.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
  t.close();
}
 
开发者ID:JasonBian,项目名称:azkaban,代码行数:70,代码来源:EmailMessage.java

示例3: connectToSmtp

import com.sun.mail.smtp.SMTPTransport; //导入依赖的package包/类
/**
  * Connects and authenticates to an SMTP server with OAuth2. You must have
  * called {@code initialize}.
  *
  * @param host Hostname of the smtp server, for example {@code
  *     smtp.googlemail.com}.
  * @param port Port of the smtp server, for example 587.
  * @param userEmail Email address of the user to authenticate, for example
  *     {@code [email protected]}.
  * @param oauthToken The user's OAuth token.
  * @param debug Whether to enable debug logging on the connection.
  *
  * @return An authenticated SMTPTransport that can be used for SMTP
  *     operations.
  */
public static SMTPTransportInfo connectToSmtp(String host, int port, String userEmail,
		String oauthToken, boolean debug) throws Exception
{
	Properties props = new Properties();
	props.put("mail.smtp.starttls.enable", "true");
	props.put("mail.smtp.starttls.required", "true");
	props.put("mail.smtp.sasl.enable", "true");
	props.put("mail.smtp.sasl.mechanisms", "XOAUTH2");
	props.put(OAuth2SaslClientFactory.OAUTH_TOKEN_PROP, oauthToken);
	Session session = Session.getInstance(props);
	session.setDebug(debug);

	final URLName unusedUrlName = null;
	SMTPTransport transport = new SMTPTransport(session, unusedUrlName);
	// If the password is non-null, SMTP tries to do AUTH LOGIN.
	transport.connect(host, port, userEmail, EMPTY_PASSWORD);
	
	SMTPTransportInfo transportInfo = new SMTPTransportInfo();
	transportInfo.session = session;
	transportInfo.smtpTransport = transport;
	return transportInfo;
}
 
开发者ID:danielebufarini,项目名称:Reminders,代码行数:38,代码来源:OAuth2Authenticator.java

示例4: send

import com.sun.mail.smtp.SMTPTransport; //导入依赖的package包/类
public static void send(String to, String sub, String msg) {
    Properties prop = System.getProperties();
    prop.put("mail.smtps.host", host);
    prop.put("mail.smtps.auth", "true");
    Session session = Session.getInstance(prop);
    
    MimeMessage message = new MimeMessage(session);
    try {
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(sub);
        message.setText(msg);
        
        SMTPTransport t = (SMTPTransport)session.getTransport("smtps");
        t.connect(host, user, password);
        t.sendMessage(message, message.getAllRecipients());
        t.close();
        
        System.out.println("Email sent to "+to);
    } catch (MessagingException ex) {
        Logger.getLogger(EMail.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
开发者ID:chaitu236,项目名称:TakServer,代码行数:24,代码来源:EMail.java

示例5: connectToSmtp

import com.sun.mail.smtp.SMTPTransport; //导入依赖的package包/类
/**
 * Connects and authenticates to an SMTP server with OAuth2. You must have
 * called {@code initialize}.
 *
 * @param host Hostname of the smtp server, for example {@code
 *     smtp.googlemail.com}.
 * @param port Port of the smtp server, for example 587.
 * @param userEmail Email address of the user to authenticate, for example
 *     {@code [email protected]}.
 * @param oauthToken The user's OAuth token.
 * @param debug Whether to enable debug logging on the connection.
 *
 * @return An authenticated SMTPTransport that can be used for SMTP
 *     operations.
 */
public static SMTPTransport connectToSmtp(String host,
                                          int port,
                                          String userEmail,
                                          String oauthToken,
                                          boolean debug) throws Exception {
  Properties props = new Properties();
  props.put("mail.smtp.starttls.enable", "true");
  props.put("mail.smtp.starttls.required", "true");
  props.put("mail.smtp.sasl.enable", "true");
  props.put("mail.smtp.sasl.mechanisms", "XOAUTH2");
  props.put(OAuth2SaslClientFactory.OAUTH_TOKEN_PROP, oauthToken);
  Session session = Session.getInstance(props);
  session.setDebug(debug);

  final URLName unusedUrlName = null;
  SMTPTransport transport = new SMTPTransport(session, unusedUrlName);
  // If the password is non-null, SMTP tries to do AUTH LOGIN.
  final String emptyPassword = "";
  transport.connect(host, port, userEmail, emptyPassword);

  return transport;
}
 
开发者ID:google,项目名称:gmail-oauth2-tools,代码行数:38,代码来源:OAuth2Authenticator.java

示例6: main

import com.sun.mail.smtp.SMTPTransport; //导入依赖的package包/类
/**
 * Authenticates to IMAP with parameters passed in on the commandline.
 */
public static void main(String args[]) throws Exception {
  if (args.length != 2) {
    System.err.println(
        "Usage: OAuth2Authenticator <email> <oauthToken>");
    return;
  }
  String email = args[0];
  String oauthToken = args[1];

  initialize();

  IMAPStore imapStore = connectToImap("imap.gmail.com",
                                      993,
                                      email,
                                      oauthToken,
                                      true);
  System.out.println("Successfully authenticated to IMAP.\n");
  SMTPTransport smtpTransport = connectToSmtp("smtp.gmail.com",
                                              587,
                                              email,
                                              oauthToken,
                                              true);
  System.out.println("Successfully authenticated to SMTP.");
}
 
开发者ID:google,项目名称:gmail-oauth2-tools,代码行数:28,代码来源:OAuth2Authenticator.java

示例7: connectToSmtp

import com.sun.mail.smtp.SMTPTransport; //导入依赖的package包/类
private SMTPTransport connectToSmtp(String host, int port, String userEmail,
                                    String oauthToken, boolean debug) throws MessagingException {

    Properties props = new Properties();
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.starttls.required", "true");
    props.put("mail.smtp.sasl.enable", "false");
    props.put("mail.smtp.ssl.enable", true);
    session = Session.getInstance(props);
    session.setDebug(debug);
    final URLName unusedUrlName = null;
    SMTPTransport transport = new SMTPTransport(session, unusedUrlName);
    // If the password is non-null, SMTP tries to do AUTH LOGIN.
    final String emptyPassword = null;
    transport.connect(host, port, userEmail, emptyPassword);

    byte[] response = String.format("user=%s\1auth=Bearer %s\1\1", userEmail,
            oauthToken).getBytes();
    response = BASE64EncoderStream.encode(response);

    transport.issueCommand("AUTH XOAUTH2 " + new String(response),
            235);

    return transport;
}
 
开发者ID:42cc,项目名称:p2psafety,代码行数:26,代码来源:GmailOAuth2Sender.java

示例8: connectToSmtp

import com.sun.mail.smtp.SMTPTransport; //导入依赖的package包/类
public SMTPTransport connectToSmtp(String userEmail, String oauthToken, Session session) throws Exception {
    final URLName unusedUrlName = null;
    SMTPTransport transport = new SMTPTransport(session, unusedUrlName);
    final String emptyPassword = null;
    final String host = "smtp.gmail.com";
    final int port = 587;
    
    transport.connect(host, port, userEmail, emptyPassword);

    byte[] response = String.format("user=%s\1auth=Bearer %s\1\1", userEmail, oauthToken).getBytes();
    response = BASE64EncoderStream.encode(response);

    transport.issueCommand("AUTH XOAUTH2 " + new String(response), 235);

    return transport;
}
 
开发者ID:nikablaine,项目名称:BatteryAlarm,代码行数:17,代码来源:BatteryStatePullService.java

示例9: connectToSmtp

import com.sun.mail.smtp.SMTPTransport; //导入依赖的package包/类
public SMTPTransport connectToSmtp(String userEmail, String oauthToken,
		Session session) throws Exception {
	final URLName unusedUrlName = null;
	SMTPTransport transport = new SMTPTransport(session, unusedUrlName);
	final String emptyPassword = null;
	final String host = "smtp.gmail.com";
	final int port = 587;

	transport.connect(host, port, userEmail, emptyPassword);

	byte[] response = String.format("user=%s\1auth=Bearer %s\1\1",
			userEmail, oauthToken).getBytes();
	response = BASE64EncoderStream.encode(response);

	transport.issueCommand("AUTH XOAUTH2 " + new String(response), 235);

	return transport;
}
 
开发者ID:nikablaine,项目名称:BatteryAlarm,代码行数:19,代码来源:Alarm.java

示例10: mailSenderEmpty

import com.sun.mail.smtp.SMTPTransport; //导入依赖的package包/类
@Test
public void mailSenderEmpty() throws IOException, MessagingException {
	Socket smtpSocket;
	String hostAddress = greenMail.getSmtp().getBindTo();
	int port = greenMail.getSmtp().getPort();

	Session smtpSession = greenMail.getSmtp().createSession();
	URLName smtpURL = new URLName(hostAddress);
	SMTPTransport smtpTransport = new SMTPTransport(smtpSession, smtpURL);

	try {
		smtpSocket = new Socket(hostAddress, port);
		smtpTransport.connect(smtpSocket);
		assertThat(smtpTransport.isConnected(),is(equalTo(true)));
		smtpTransport.issueCommand("MAIL FROM: <>", -1);
		assertThat("250 OK", equalToIgnoringWhiteSpace(smtpTransport.getLastServerResponse()));
	} finally {
		smtpTransport.close();
	}
}
 
开发者ID:greenmail-mail-test,项目名称:greenmail,代码行数:21,代码来源:SMTPCommandTest.java

示例11: sendMail

import com.sun.mail.smtp.SMTPTransport; //导入依赖的package包/类
public static void sendMail(String to, String subject, String content) throws MessagingException
{    
    String server_email = TheConfig.getProperty(TheConfig.SYSTEMEMAIL_ADDRESS);
    String server_pwd = TheConfig.getProperty(TheConfig.SYSTEMEMAIL_PASSWORD);
            
    Properties props = System.getProperties();
    props.put("mail.smtps.host",TheConfig.getProperty("mail.smtps.host"));
    props.put("mail.smtps.auth","true");
    Session session = Session.getInstance(props, null);
    
    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(server_email));
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
    msg.setSubject(subject);
    msg.setText(content);
    msg.setHeader("X-Mailer", "Sisob Data Extractor System");
    msg.setSentDate(new Date());
    
    SMTPTransport t =(SMTPTransport)session.getTransport("smtps");
    t.connect(TheConfig.getProperty("mail.smtps.host"), server_email, server_pwd);
    t.sendMessage(msg, msg.getAllRecipients());
    
    LOG.info("Email Response To " + to + ": " + t.getLastServerResponse());
    t.close(); 
}
 
开发者ID:eduardoguzman,项目名称:sisob-data-extractor,代码行数:26,代码来源:Mailer.java

示例12: registerHealthchecks

import com.sun.mail.smtp.SMTPTransport; //导入依赖的package包/类
private void registerHealthchecks() {
    SystemResource.registerHealthcheck(new Healthcheck() {
        @Override
        public String getName() {
            return "SMTP";
        }

        @Override
        protected Result check() throws Exception {
            final Properties properties = new Properties();
            properties.put("mail.transport.protocol", "smtp");
            Transport transport = Session.getInstance(properties).getTransport();
            transport.connect(FenixEduAcademicConfiguration.getConfiguration().getMailSmtpHost(), null, null);
            String response = ((SMTPTransport) transport).getLastServerResponse();
            transport.close();
            return Result.healthy("SMTP server returned response: " + response);
        }
    });
}
 
开发者ID:FenixEdu,项目名称:fenixedu-academic,代码行数:20,代码来源:FenixInitializer.java

示例13: connectToSmtp

import com.sun.mail.smtp.SMTPTransport; //导入依赖的package包/类
private SMTPTransport connectToSmtp(Session session, String host, int port, String userEmail,
                                    String oauthToken) throws MessagingException {

    final URLName unusedUrlName = null;
    SMTPTransport transport = new SMTPTransport(session, unusedUrlName);

    // If the password is non-null, SMTP tries to do AUTH LOGIN.
    final String emptyPassword = null;
    transport.connect(host, port, userEmail, emptyPassword);

    byte[] response = String.format("user=%s\1auth=Bearer %s\1\1", userEmail,
            oauthToken).getBytes();
    response = BASE64EncoderStream.encode(response);

    transport.issueCommand("AUTH XOAUTH2 " + new String(response),
            235);

    return transport;
}
 
开发者ID:peter-tackage,项目名称:open-secret-santa,代码行数:20,代码来源:GmailTransport.java

示例14: send

import com.sun.mail.smtp.SMTPTransport; //导入依赖的package包/类
public static void send(final String username, final String password, String recipientEmail, String ccEmail, String title, String message, MailConsts mailConsts) throws AddressException, MessagingException {
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    Properties props = System.getProperties();
    props.setProperty("mail.smtps.host", mailConsts.getHost());
    props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.setProperty("mail.smtp.socketFactory.fallback", "false");
    props.setProperty("mail.smtp.port", String.valueOf(mailConsts.getPort()));
    props.setProperty("mail.smtp.socketFactory.port", String.valueOf(mailConsts.getPort()));
    props.setProperty("mail.smtps.auth", "true");
    props.put("mail.smtps.quitwait", "false");
    Session session = Session.getInstance(props, null);
    final MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(username + "@" + mailConsts.getPostfix()));
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false));
    if (ccEmail.length() > 0) {
        msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false));
    }
    msg.setSubject(title);
    msg.setText(message, "utf-8");
    msg.setSentDate(new Date());
    SMTPTransport t = (SMTPTransport) session.getTransport("smtps");
    t.connect(mailConsts.getHost(), username, password);
    t.sendMessage(msg, msg.getAllRecipients());
    t.close();
}
 
开发者ID:indiyskiy,项目名称:WorldOnline,代码行数:27,代码来源:MailSender.java

示例15: senderConnect

import com.sun.mail.smtp.SMTPTransport; //导入依赖的package包/类
public void senderConnect() throws NoSuchProviderException, MessagingException {
    senderSession = Session.getInstance(pManager.getSenderProps());
    //senderSession.setDebugOut(pManager.get_Log_Stream());
    
    transport = (SMTPTransport)(senderSession.getTransport("smtp"));
    transport.connect(pManager.get_SENDER_User(), pManager.get_SENDER_Pass());
}
 
开发者ID:adbenitez,项目名称:MailCopier,代码行数:8,代码来源:MailCopier.java


注:本文中的com.sun.mail.smtp.SMTPTransport类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。