下面列出了javax.mail.Authenticator#javax.mail.Transport 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void sendEmail(String fromEmail, String toEmail, String subject, String textBody, String htmlBody) {
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromEmail));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
message.setSubject(subject);
// Set the message
createMultiMimePart(message, textBody, htmlBody);
Transport.send(message);
}
catch (MessagingException e) {
throw new HoldMailException("Failed to send email : " + e.getMessage(), e);
}
}
/**
* @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
*/
public void execute(JobExecutionContext context)
throws JobExecutionException {
JobDataMap data = context.getMergedJobDataMap();
MailInfo mailInfo = populateMailInfo(data, createMailInfo());
getLog().info("Sending message " + mailInfo);
try {
MimeMessage mimeMessage = prepareMimeMessage(mailInfo);
Transport.send(mimeMessage);
} catch (MessagingException e) {
throw new JobExecutionException("Unable to send mail: " + mailInfo,
e, false);
}
}
/** */
public void testReceivedHeader() throws Exception
{
MimeMessage message = new MimeMessage(this.session);
message.addRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
message.setFrom(new InternetAddress("[email protected]"));
message.setSubject("barf");
message.setText("body");
Transport.send(message);
assertEquals(1, this.wiser.getMessages().size());
String[] receivedHeaders = this.wiser.getMessages().get(0).getMimeMessage().getHeader("Received");
assertEquals(1, receivedHeaders.length);
}
private void putOnTransport(Session session, Message msg) throws SenderException {
// connect to the transport
Transport transport = null;
try {
transport = session.getTransport("smtp");
transport.connect(getSmtpHost(), getCredentialFactory().getUsername(), getCredentialFactory().getPassword());
if (log.isDebugEnabled()) {
log.debug("MailSender [" + getName() + "] connected transport to URL [" + transport.getURLName() + "]");
}
transport.sendMessage(msg, msg.getAllRecipients());
} catch (Exception e) {
throw new SenderException("MailSender [" + getName() + "] cannot connect send message to smtpHost [" + getSmtpHost() + "]", e);
} finally {
if (transport != null) {
try {
transport.close();
} catch (MessagingException e1) {
log.warn("MailSender [" + getName() + "] got exception closing connection", e1);
}
}
}
}
public void send(String email) throws SmtpEmailSenderException {
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(FROM));
message.addRecipient(TO, new InternetAddress(email));
message.setSubject("Welcome!");
message.setText("It's our pleasure to have you as a member :)");
Transport.send(message);
} catch (MessagingException e) {
throw new SmtpEmailSenderException(e);
}
}
@Override
public void sendHtmlWithAttachment(String to, String subj, String body,
QrHolder[] attachmentData) throws Exception {
MimeMessage message = new MimeMessage(session);
message.setFrom(from);
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(subj, "UTF-8");
Multipart multipart = new MimeMultipart();
MimeBodyPart bodyMessagePart = new MimeBodyPart();
bodyMessagePart.setContent(body, TEXT_HTML_CHARSET_UTF_8);
multipart.addBodyPart(bodyMessagePart);
attachQRs(multipart, attachmentData);
attachCSV(multipart, attachmentData);
message.setContent(multipart);
Transport.send(message);
log.trace("Mail to {} was sent. Subj : {}, body : {}", to, subj, body);
}
public static void main(String[] args) throws Exception {
final Properties props = new Properties();
props.load(ClassLoader.getSystemResourceAsStream("mail.properties"));
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(props.getProperty("smtp.username"), props.getProperty("smtp.pass"));
}
});
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(props.getProperty("address.sender")));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(props.getProperty("address.recipient")));
message.setSubject("Test JavaMail");
message.setText("Hello!\n\n\tThis is a test message from JavaMail.\n\nThank you.");
Transport.send(message);
log.info("Message was sent");
}
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));
}
private void sendEmail(String email, String name, String subject, String content) throws MessagingException {
if (email == null || email.isEmpty()) {
LOGGER.log(Level.WARNING, "Cannot send mail, email is empty");
return;
}
try {
InternetAddress emailAddress = new InternetAddress(email, name);
Message message = new MimeMessage(mailSession);
message.addRecipient(Message.RecipientType.TO, emailAddress);
message.setSubject(subject);
message.setSentDate(new Date());
message.setContent(content, "text/html; charset=utf-8");
message.setFrom();
Transport.send(message);
} catch (UnsupportedEncodingException e) {
String logMessage = "Unsupported encoding: " + e.getMessage();
LOGGER.log(Level.SEVERE, logMessage, e);
}
}
/**
* Send a calendar message.
*
* @param mail
* The mail to send
* @param transport
* the smtp transport object
* @param session
* the smtp session object
* @throws AddressException
* If invalid address
* @throws SendFailedException
* If an error occurred during sending
* @throws MessagingException
* If a messaging error occurred
*/
protected static void sendMessageCalendar( MailItem mail, Transport transport, Session session ) throws MessagingException
{
Message msg = prepareMessage( mail, session );
msg.setHeader( HEADER_NAME, HEADER_VALUE );
MimeMultipart multipart = new MimeMultipart( );
BodyPart msgBodyPart = new MimeBodyPart( );
msgBodyPart.setDataHandler( new DataHandler( new ByteArrayDataSource( mail.getMessage( ),
AppPropertiesService.getProperty( PROPERTY_MAIL_TYPE_HTML ) + AppPropertiesService.getProperty( PROPERTY_CHARSET ) ) ) );
multipart.addBodyPart( msgBodyPart );
BodyPart calendarBodyPart = new MimeBodyPart( );
calendarBodyPart.setContent( mail.getCalendarMessage( ),
AppPropertiesService.getProperty( PROPERTY_MAIL_TYPE_CALENDAR ) + AppPropertiesService.getProperty( PROPERTY_CHARSET )
+ AppPropertiesService.getProperty( PROPERTY_CALENDAR_SEPARATOR )
+ AppPropertiesService.getProperty( mail.getCreateEvent( ) ? PROPERTY_CALENDAR_METHOD_CREATE : PROPERTY_CALENDAR_METHOD_CANCEL ) );
calendarBodyPart.addHeader( HEADER_NAME, CONSTANT_BASE64 );
multipart.addBodyPart( calendarBodyPart );
msg.setContent( multipart );
sendMessage( msg, transport );
}
@Nullable
@Override
protected String doInBackground(String... strings) {
try {
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes()));
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setDataHandler(handler);
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
Transport.send(message);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Sends an email.
* @return true if no error occurred, false otherwise
*/
public static boolean sendEmail( final InternetAddress from, final InternetAddress to, final InternetAddress cc, final String subject, final String body ) {
LOGGER.info( "Sending email to: " + to.toString() + ", subject: " + subject );
final Session session = Session.getDefaultInstance( new Properties(), null );
try {
final Message message = new MimeMessage( session );
message.setFrom( from );
message.addRecipient( Message.RecipientType.TO, to );
if ( cc != null )
message.addRecipient( Message.RecipientType.CC, cc );
message.addRecipient( Message.RecipientType.BCC, ADMIN_EMAIL );
message.setSubject( "[Sc2gears Database] " + subject );
message.setText( body );
Transport.send( message );
return true;
} catch ( final Exception e ) {
LOGGER.log( Level.SEVERE, "Failed to send email!", e );
return false;
}
}
public static ConnectionStrategy newConnectionStrategy(final String username, final String password) {
return new ConnectionStrategy() {
@Override
public void connect(Transport transport) throws MessagingException {
transport.connect(username, password);
}
@Override
public String toString() {
return "ConnectionStrategy{" +
"username=" + username +
'}';
}
};
}
@Override
public void sendNotification(Notification notification)
throws NotificationException
{
Session session = createSession();
MimeMessage msg = new MimeMessage(session);
try {
msg.setFrom(newAddress(from));
msg.setSender(newAddress(from));
msg.setRecipients(MimeMessage.RecipientType.TO, addresses(this.to));
msg.setRecipients(MimeMessage.RecipientType.CC, addresses(this.cc));
msg.setRecipients(MimeMessage.RecipientType.BCC, addresses(this.bcc));
msg.setSubject(subject);
msg.setText(body(notification), "utf-8", isHtml ? "html" : "plain");
Transport.send(msg);
}
catch (MessagingException | IOException | TemplateException ex) {
throw Throwables.propagate(ex);
}
}
/**
* Runs the task, which sends all email messages that have been queued.
*/
public void run() {
try {
Iterator messageIterator = messages.iterator();
while (messageIterator.hasNext()) {
try {
Thread.sleep(6000);
Message message = (Message) messageIterator.next();
Transport.send(message);
} catch (Exception me) {
me.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
this.messages.clear();
}
}
public void notify(String subject, String message) {
if (this.from != null && !this.to.isEmpty()) {
Message msg = new MimeMessage(this.session);
try {
Address[] recipients = this.to.toArray(new Address[this.to.size()]);
Transport transport = this.session.getTransport();
msg.setFrom(this.from);
msg.addRecipients(Message.RecipientType.TO, recipients);
msg.setSubject(subject);
msg.setText(message);
transport.connect();
transport.sendMessage(msg, recipients);
transport.close();
} catch (MessagingException e) {
logger.error("Error while sending notification message '" + subject + "'", e);
}
} else {
logger.warn("From is null or to is empty. Notification won't be send.");
}
}
@Test
public void sendReport() throws MessagingException {
mockStatic(Transport.class);
expect(ReportConfigurator.getInstance()).andReturn(mockReportConfigurator);
expect(mockReportConfigurator.getSmtpServerName()).andReturn("localhost");
expect(mockReportConfigurator.getSmtpServerPort()).andReturn("25");
expect(mockReportConfigurator.getAddressesTo()).andReturn(new String[]{ "userTo" });
expect(mockReportConfigurator.getAddressesCc()).andReturn(new String[0]);
expect(mockReportConfigurator.getAddressesBcc()).andReturn(new String[0]);
expect(mockReportConfigurator.getAddressFrom()).andReturn("userFrom");
Transport.send(isA(Message.class));
replayAll();
triggerRun();
verifyAll();
}
@Test( expected = MailReportSendException.class)
public void errorOnSend() throws MessagingException {
mockStatic(Transport.class);
expect(ReportConfigurator.getInstance()).andReturn(mockReportConfigurator);
expect(mockReportConfigurator.getSmtpServerName()).andReturn("localhost");
expect(mockReportConfigurator.getSmtpServerPort()).andReturn("25");
expect(mockReportConfigurator.getAddressesTo()).andReturn(new String[]{ "userTo" });
expect(mockReportConfigurator.getAddressesCc()).andReturn(new String[0]);
expect(mockReportConfigurator.getAddressesBcc()).andReturn(new String[0]);
expect(mockReportConfigurator.getAddressFrom()).andReturn("userFrom");
Transport.send(isA(Message.class));
expectLastCall().andThrow(new MessagingException());
replayAll();
triggerRun();
verifyAll();
}
@Test
public void sendAuthenticatedMessage() throws MessagingException, AlertException {
TestProperties testProperties = new TestProperties();
EmailProperties emailProperties = new EmailProperties(createEmailGlobalConfigEntity());
FreemarkerTemplatingService freemarkerTemplatingService = new FreemarkerTemplatingService();
EmailMessagingService emailMessagingService = new EmailMessagingService(emailProperties, freemarkerTemplatingService);
Session mockSession = Mockito.mock(Session.class);
Transport mockTransport = Mockito.mock(Transport.class);
Mockito.doNothing().when(mockTransport).connect();
Mockito.doNothing().when(mockTransport).close();
Mockito.when(mockSession.getTransport(Mockito.anyString())).thenReturn(mockTransport);
Mockito.when(mockSession.getProperties()).thenReturn(testProperties.getProperties());
Message message = new MimeMessage(mockSession);
Mockito.doNothing().when(mockTransport).sendMessage(Mockito.eq(message), Mockito.any());
emailMessagingService.sendMessages(emailProperties, mockSession, List.of(message));
}
/**
* Send a regular email.
*
* @param toEmail receiver's email
* @param replyTo email for reply or null
* @param subject
* @param body
*/
public static void sendEmail(String toEmail, String replyTo, String subject, String body) {
Session session = Session.getDefaultInstance(new Properties(), null);
MimeMessage message = new MimeMessage(session);
try {
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(toEmail));
message.setSubject(subject);
message.setText(body);
// set email for reply
if (replyTo != null) {
message.addHeader("Reply-To", replyTo);
}
Transport.send(message);
} catch (MessagingException e){
System.err.println("Email could not be sent.");
}
}
/**
* Sends e-mail to the specified recipients.
*
* @param recipients
* Comma separated list of recipient e-mail addresses
* @param subject
* Subject for the e-mail
* @param messageBody
* The body for the e-mail
*/
public void send(String recipients, String subject, String messageBody) {
Message message = new MimeMessage(session);
try {
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(recipients));
message.setSubject(subject);
message.setText(messageBody);
Transport.send(message);
logger.info("Successfully sent e-mail to {} . The e-mail "
+ "message subject was: \"{}\", and body was: \"{}\"",
recipients, subject, messageBody);
} catch (MessagingException e) {
// Since this is a serious issue log the error and send an e-mail
// via logback
logger.error(Markers.email(),
"Failed sending e-mail for agencyId={}. The e-mail config "
+ "file {} specified by the Java property {} contains the "
+ "login info to the SMTP server. Exception message: {}. "
+ "The e-mail message subject was: \"{}\", and body "
+ "was: \"{}\"",
AgencyConfig.getAgencyId(), emailConfigFile.getID(),
emailConfigFile.getValue(), e.getMessage(), subject,
messageBody);
}
}
/**
* Obtain and connect a Transport from the underlying JavaMail Session,
* passing in the specified host, port, username, and password.
* @return the connected Transport object
* @throws MessagingException if the connect attempt failed
* @since 4.1.2
* @see #getTransport
* @see #getHost()
* @see #getPort()
* @see #getUsername()
* @see #getPassword()
*/
protected Transport connectTransport() throws MessagingException {
String username = getUsername();
String password = getPassword();
if ("".equals(username)) { // probably from a placeholder
username = null;
if ("".equals(password)) { // in conjunction with "" username, this means no password to use
password = null;
}
}
Transport transport = getTransport(getSession());
transport.connect(getHost(), getPort(), username, password);
return transport;
}
/**
* Obtain a Transport object from the given JavaMail Session,
* using the configured protocol.
* <p>Can be overridden in subclasses, e.g. to return a mock Transport object.
* @see javax.mail.Session#getTransport(String)
* @see #getSession()
* @see #getProtocol()
*/
protected Transport getTransport(Session session) throws NoSuchProviderException {
String protocol = getProtocol();
if (protocol == null) {
protocol = session.getProperty("mail.transport.protocol");
if (protocol == null) {
protocol = DEFAULT_PROTOCOL;
}
}
return session.getTransport(protocol);
}
public static TransportStrategy newSessiontStrategy() {
return new TransportStrategy() {
@Override
public Transport getTransport(Session session) throws NoSuchProviderException {
return session.getTransport();
}
};
}
/**
* Send the mail
*
* @param aMailhost mail server
* @param aFrom from address
* @param aToList comma-separated recipient list
* @param aSubject mail subject
* @param aText mail body
* @throws Exception if sending message fails
*/
private void sendMail(String aMailhost, String aFrom, String aToList,
String aSubject, String aText)
throws Exception
{
// Get system properties
final Properties props = System.getProperties();
// Setup mail server
props.put("mail.smtp.host", aMailhost);
// Get session
final Session session = Session.getDefaultInstance(props, null);
// Define message
final MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(aFrom));
final StringTokenizer t = new StringTokenizer(aToList, ", ", false);
while (t.hasMoreTokens()) {
message.addRecipient(
MimeMessage.RecipientType.TO,
new InternetAddress(t.nextToken()));
}
message.setSubject(aSubject);
message.setText(aText);
Transport.send(message);
}
public static TransportStrategy newUrlNameStrategy(final URLName urlName) {
return new TransportStrategy() {
@Override
public Transport getTransport(Session session) throws NoSuchProviderException {
return session.getTransport(urlName);
}
};
}
private boolean sendMail(String toEmail, String subject, String body) {
try {
Properties props = System.getProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.port", mailProperties.getSmtp().getPort());
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
session.setDebug(true);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(mailProperties.getFrom(), mailProperties.getFromName()));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
msg.setSubject(subject);
msg.setContent(body, "text/html");
Transport transport = session.getTransport();
transport.connect(mailProperties.getSmtp().getHost(), mailProperties.getSmtp().getUsername(), mailProperties.getSmtp().getPassword());
transport.sendMessage(msg, msg.getAllRecipients());
return true;
} catch (Exception ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, ex.getMessage(), ex);
}
return false;
}
public void sendMessages() throws MessagingException {
Transport transport = null;
try {
URLName url = new URLName("smtp", host, port, "", username, password);
if (session == null) {
createSession();
}
transport = new com.sun.mail.smtp.SMTPTransport(session, url);
transport.connect(host, port, username, password);
for (MimeMessage message : messages) {
// Attempt to send message, but catch exceptions caused by invalid
// addresses so that other messages can continue to be sent.
try {
transport.sendMessage(message,
message.getRecipients(MimeMessage.RecipientType.TO));
}
catch (AddressException | SendFailedException ae) {
Log.error(ae.getMessage(), ae);
}
}
}
finally {
if (transport != null) {
try {
transport.close();
}
catch (MessagingException e) { /* ignore */ }
}
}
}
public boolean send(List<String> recipients,String from,String subject,MimeMultipart content) {
if(from==null) from=defaultFrom;
if(subject==null) subject=defaultSubject;
try{
// Properties props=new Properties();
// props.put("mail.smtp.host",smtpServer);
Session session=Session.getDefaultInstance(mailProps,null);
MimeMessage message=new MimeMessage(session);
if(subject!=null) message.setSubject(subject);
if(from!=null) message.setFrom(new InternetAddress(from));
message.setContent(content);
Transport transport = session.getTransport("smtp");
if(smtpPort>0) transport.connect(smtpServer,smtpPort,smtpUser,smtpPass);
else transport.connect(smtpServer,smtpUser,smtpPass);
Address[] recipientAddresses=new Address[recipients.size()];
for(int i=0;i<recipientAddresses.length;i++){
recipientAddresses[i]=new InternetAddress(recipients.get(i));
}
transport.sendMessage(message,recipientAddresses);
return true;
}
catch(MessagingException me){
logging.warn("Couldn't send email",me);
return false;
}
}
private void sendNotification(String sendTo, String sendCC, String subject, String message) {
try {
// create a message
Message msg = new MimeMessage(emailSession);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(IBMonitorSvc.emailReplyTo);
msg.setFrom(addressFrom);
if (!sendTo.equals("")){
InternetAddress[] addressTo = parseRecipients(sendTo);
msg.setRecipients(Message.RecipientType.TO, addressTo);
}
if (!sendCC.equals("")){
InternetAddress[] addressCC = parseRecipients(sendCC);
msg.setRecipients(Message.RecipientType.CC, addressCC);
}
// Setting the Subject and Content Type
msg.setSubject(subject);
message = message + CRLF + CRLF + "This is an automated email. Please do not reply to sender.";
msg.setContent(message, "text/plain");
Transport.send(msg);
} catch(MessagingException me) {
logger.info("Error sending secure email message using password auth - " + me.getMessage());
} catch (Exception e) {
logger.info("Exception caught when attempting to send email: " + e.getMessage());
}
}