本文整理汇总了Java中javax.mail.Session.getDefaultInstance方法的典型用法代码示例。如果您正苦于以下问题:Java Session.getDefaultInstance方法的具体用法?Java Session.getDefaultInstance怎么用?Java Session.getDefaultInstance使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类javax.mail.Session
的用法示例。
在下文中一共展示了Session.getDefaultInstance方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: sendToAdmin
import javax.mail.Session; //导入方法依赖的package包/类
@Override
public boolean sendToAdmin(final String institutionEmailAddress, final String applicationMessage) {
String[] to = new String[]{"[email protected]"};
setupProperties();
Session session = Session.getDefaultInstance(properties);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(username));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for (int i = 0; i < to.length; i++) {
toAddress[i] = new InternetAddress(to[i]);
}
for (int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(APPLICATION_SUBJECT);
message.setText(applicationBody + "Email: " + institutionEmailAddress + "\nMessage: " + applicationMessage);
Transport transport = session.getTransport("smtp");
transport.connect(host, username, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
LOGGER.info("Email sent to Admin");
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
示例2: getStore
import javax.mail.Session; //导入方法依赖的package包/类
private Store getStore() throws MessagingException {
if (store == null) {
// This is the JavaMail session.
Session session;
// Initialize JavaMail session.
session = Session.getDefaultInstance(new Properties(), null);
// Connect to e-mail server
store = session.getStore(mailProviderType);
store.connect(mailServer, mailUser, mailPassword);
}
return store;
}
示例3: sendHtmlMail
import javax.mail.Session; //导入方法依赖的package包/类
/**
* 以HTML格式发送邮件
*
* @param mailInfo
* 待发送的邮件信息
*/
public boolean sendHtmlMail(MailSenderObj mailInfo) {
// 判断是否需要身份认证
MyAuthenticator authenticator = null;
Properties pro = mailInfo.getProperties();
// 如果需要身份认证,则创建一个密码验证器
if (mailInfo.isValidate()) {
authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
}
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
sendMailSession.setDebug(true);// 设置debug模式 在控制台看到交互信息
try {
// 根据session创建一个邮件消息
Message mailMessage = new MimeMessage(sendMailSession);
// 创建邮件发送者地址
Address from = new InternetAddress(mailInfo.getFromAddress());
// 设置邮件消息的发送者
mailMessage.setFrom(from);
// 创建邮件的接收者地址,并设置到邮件消息中
String[] asToAddr = mailInfo.getToAddress();
if (asToAddr == null) {
logger.debug("邮件发送失败,收信列表为空" + mailInfo);
return false;
}
for (int i=0; i<asToAddr.length; i++) {
if (asToAddr[i] == null || asToAddr[i].equals("")) {
continue;
}
Address to = new InternetAddress(asToAddr[i]);
// Message.RecipientType.TO属性表示接收者的类型为TO
mailMessage.addRecipient(Message.RecipientType.TO, to);
}
// 设置邮件消息的主题
mailMessage.setSubject(mailInfo.getSubject());
// 设置邮件消息发送的时间
mailMessage.setSentDate(new Date());
// MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
Multipart mainPart = new MimeMultipart();
// 创建一个包含HTML内容的MimeBodyPart
BodyPart html = new MimeBodyPart();
// 设置HTML内容
html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
mainPart.addBodyPart(html);
// 将MiniMultipart对象设置为邮件内容
mailMessage.setContent(mainPart);
// 发送邮件
Transport.send(mailMessage);
logger.info("发送邮件成功。" + mailInfo);
return true;
} catch (MessagingException ex) {
logger.error("发送邮件失败:" + ex.getMessage() + Arrays.toString(ex.getStackTrace()));
}
return false;
}
示例4: createEmailMessage
import javax.mail.Session; //导入方法依赖的package包/类
/**
* Bereitet den Mailinhalt zum Senden vor.
*
* @throws MessagingException -
* @throws UnsupportedEncodingException -
*/
public void createEmailMessage() throws MessagingException, UnsupportedEncodingException {
mailSession = Session.getDefaultInstance(emailProperties, null);
emailMessage = new MimeMessage(mailSession);
emailMessage.setFrom(new InternetAddress(fromEmail, fromEmail));
for (String toEmail : toEmailList) {
emailMessage.addRecipient(Message.RecipientType.TO,
new InternetAddress(toEmail));
}
emailMessage.setSubject(emailSubject);
emailMessage.setContent(emailBody, "text/html");
}
示例5: sendSetupMail
import javax.mail.Session; //导入方法依赖的package包/类
@Override
public boolean sendSetupMail(final String[] to, final String code, final String subject, final String body) {
setupProperties();
Session session = Session.getDefaultInstance(properties);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(username));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for (int i = 0; i < to.length; i++) {
toAddress[i] = new InternetAddress(to[i]);
}
for (int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
if (subject == null || body == null) {
message.setSubject(SETUP_SUBJECT);
message.setText(setupBody + code);
} else {
message.setSubject(subject);
message.setText(body + code);
}
Transport transport = session.getTransport("smtp");
transport.connect(host, username, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
LOGGER.info("Setup email has been sent.");
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
示例6: testCaseSensitivity
import javax.mail.Session; //导入方法依赖的package包/类
/**
* MNT-9289
*
* Change in case in email Subject causes DuplicateChildNodeNameException
*/
public void testCaseSensitivity() throws Exception
{
NodeRef person = personService.getPerson(TEST_USER);
String TEST_EMAIL="[email protected]";
NodeRef testUserHomeFolder = (NodeRef)nodeService.getProperty(person, ContentModel.PROP_HOMEFOLDER);
if(person == null)
{
logger.debug("new person created");
Map<QName, Serializable> props = new HashMap<QName, Serializable>();
props.put(ContentModel.PROP_USERNAME, TEST_USER);
props.put(ContentModel.PROP_EMAIL, TEST_EMAIL);
person = personService.createPerson(props);
}
nodeService.setProperty(person, ContentModel.PROP_EMAIL, TEST_EMAIL);
Set<String> auths = authorityService.getContainedAuthorities(null, "GROUP_EMAIL_CONTRIBUTORS", true);
if(!auths.contains(TEST_USER))
{
authorityService.addAuthority("GROUP_EMAIL_CONTRIBUTORS", TEST_USER);
}
String companyHomePathInStore = "/app:company_home";
String storePath = "workspace://SpacesStore";
StoreRef storeRef = new StoreRef(storePath);
NodeRef storeRootNodeRef = nodeService.getRootNode(storeRef);
List<NodeRef> nodeRefs = searchService.selectNodes(storeRootNodeRef, companyHomePathInStore, null, namespaceService, false);
NodeRef companyHomeNodeRef = nodeRefs.get(0);
assertNotNull("company home is null", companyHomeNodeRef);
String TEST_CASE_SENSITIVITY_SUBJECT = "Test (Mail)";
String testUserHomeDBID = ((Long)nodeService.getProperty(testUserHomeFolder, ContentModel.PROP_NODE_DBID)).toString() + "@Alfresco.com";
String from = TEST_EMAIL;
String to = testUserHomeDBID;
String content = "hello world";
Session sess = Session.getDefaultInstance(new Properties());
assertNotNull("sess is null", sess);
SMTPMessage msg = new SMTPMessage(sess);
InternetAddress[] toa = { new InternetAddress(to) };
EmailDelivery delivery = new EmailDelivery(to, from, null);
msg.setFrom(new InternetAddress(TEST_EMAIL));
msg.setRecipients(Message.RecipientType.TO, toa);
msg.setContent(content, "text/plain");
msg.setSubject(TEST_CASE_SENSITIVITY_SUBJECT);
ByteArrayOutputStream bos1 = new ByteArrayOutputStream();
msg.writeTo(bos1);
InputStream is = IOUtils.toInputStream(bos1.toString());
assertNotNull("is is null", is);
SubethaEmailMessage m = new SubethaEmailMessage(is);
folderEmailMessageHandler.setOverwriteDuplicates(false);
emailService.importMessage(delivery, m);
QName safeQName = QName.createQNameWithValidLocalName(NamespaceService.CONTENT_MODEL_1_0_URI, TEST_CASE_SENSITIVITY_SUBJECT);
List<ChildAssociationRef> assocs = nodeService.getChildAssocs(testUserHomeFolder, ContentModel.ASSOC_CONTAINS, safeQName);
assertEquals(1, assocs.size());
msg.setSubject(TEST_CASE_SENSITIVITY_SUBJECT.toUpperCase());
ByteArrayOutputStream bos2 = new ByteArrayOutputStream();
msg.writeTo(bos2);
is = IOUtils.toInputStream(bos2.toString());
assertNotNull("is is null", is);
m = new SubethaEmailMessage(is);
folderEmailMessageHandler.setOverwriteDuplicates(false);
emailService.importMessage(delivery, m);
safeQName = QName.createQNameWithValidLocalName(NamespaceService.CONTENT_MODEL_1_0_URI, TEST_CASE_SENSITIVITY_SUBJECT.toUpperCase() + "(1)");
assocs = nodeService.getChildAssocs(testUserHomeFolder, ContentModel.ASSOC_CONTAINS, safeQName);
assertEquals(1, assocs.size());
}
示例7: createEmail
import javax.mail.Session; //导入方法依赖的package包/类
public static MimeMessage createEmail(String to, String from, String subject,
String bodyText) throws MessagingException{
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
MimeMessage email = new MimeMessage(session);
InternetAddress tAddress = new InternetAddress(to);
InternetAddress fAddress = new InternetAddress(from);
email.setFrom(fAddress);
email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
email.setSubject(subject);
email.setText(bodyText);
return email;
}
示例8: constructFromMimeMessage
import javax.mail.Session; //导入方法依赖的package包/类
@Test
public void constructFromMimeMessage() throws Exception {
MimePackage message = new MimePackage(new MimeMessage(Session.getDefaultInstance(new Properties()),
new FileInputStream(mailMessagePath)));
assertEquals(4, message.getRegularPartCount());
assertEquals(2, message.getAttachmentPartCount());
}
示例9: createEmail
import javax.mail.Session; //导入方法依赖的package包/类
private static MimeMessage createEmail(String to, String from, String subject, String bodyText) throws MessagingException {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
MimeMessage email = new MimeMessage(session);
email.setFrom(new InternetAddress(from));
email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
email.setSubject(subject);
email.setText(bodyText);
return email;
}
示例10: createMessage
import javax.mail.Session; //导入方法依赖的package包/类
public static Message createMessage(String to, String from, String sub, String bodyText, boolean isHtml, List<File> attachments) throws MessagingException, IOException {
if (to == null || from == null) {
System.out.println("Fields cannot be empty");
return null;
}
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
MimeMessage email = new MimeMessage(session);
if (!from.equals(""))
email.setFrom(new InternetAddress(from));
if (!to.equals(""))
email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
//if (!sub.equals(""))
email.setSubject(sub);
if (attachments == null || attachments.isEmpty()) {
if (isHtml)
email.setContent(bodyText, "text/html");
else
email.setText(bodyText);
} else {
MimeBodyPart mimeBodyPart = new MimeBodyPart();
if (isHtml)
mimeBodyPart.setContent(bodyText, "text/plain");
else
mimeBodyPart.setContent(bodyText, "text/plain");
for (File attachmentFile : attachments) {
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);
mimeBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(attachmentFile);
mimeBodyPart.setDataHandler(new DataHandler(source));
mimeBodyPart.setFileName(attachmentFile.getName());
multipart.addBodyPart(mimeBodyPart);
email.setContent(multipart);
}
}
Message message = createFromMimeMessage(email);
return message;
}
示例11: sendPassword
import javax.mail.Session; //导入方法依赖的package包/类
public static void sendPassword(String receiveMailAccount, String password) throws Exception {
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.host", myEmailSMTPHost);
props.setProperty("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
session.setDebug(true);
MimeMessage message = createMimeMessage(session, myEmailAccount, receiveMailAccount, password);
Transport transport = session.getTransport();
transport.connect(myEmailAccount, myEmailPassword);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
示例12: sendMail
import javax.mail.Session; //导入方法依赖的package包/类
/**
* Send mail.
*
* @param from
* Sender's email ID needs to be mentioned
* @param to
* Recipient's email ID needs to be mentioned.
* @param subject
* the subject
* @throws MessagingException
*/
public void sendMail(String from, String to, String subject, String body) throws MessagingException {
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.port", Integer.toString(port));
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
Transport transport = null;
try {
transport = session.getTransport();
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set Subject: header field
message.setSubject(subject);
// Now set the actual message
message.setText(body);
// Send message
transport.send(message);
System.out.println("Sent message successfully....");
} finally {
if (transport != null) {
transport.close();
}
}
}
示例13: serviceShouldAddHeaderWhenMessageWithCharset
import javax.mail.Session; //导入方法依赖的package包/类
@Test
public void serviceShouldAddHeaderWhenMessageWithCharset() throws Exception {
String response = "{\"results\":" +
"{\"[email protected]\":{" +
" \"mailboxId\":\"cfe49390-f391-11e6-88e7-ddd22b16a7b9\"," +
" \"mailboxName\":\"JAMES\"," +
" \"confidence\":50.07615280151367}" +
"}," +
"\"errors\":{}}";
mockServerClient.when(
HttpRequest.request()
.withMethod("POST")
.withPath("/email/classification/predict")
.withHeader("Content-Type", JSON_CONTENT_TYPE_UTF8)
.withQueryStringParameter(new Parameter("recipients", "[email protected]", "[email protected]"))
.withBody(new StringBody(
"{\"messageId\":\"524e4f85-2d2f-4927-ab98-bd7a2f689773\"," +
"\"from\":[{\"name\":\"User\",\"address\":\"[email protected]\"}]," +
"\"recipients\":{\"to\":[{\"name\":\"User\",\"address\":\"[email protected]\"}]," +
"\"cc\":[]," +
"\"bcc\":[]}," +
"\"subject\":[\"éééééààààà\"]," +
"\"textBody\":\"éééééààààà\"," +
"\"date\":\"2017-04-20T03:01:20Z\"}",
Charsets.UTF_8)),
Times.exactly(1))
.respond(HttpResponse.response(response));
FakeMailetConfig config = FakeMailetConfig.builder()
.setProperty(SERVICE_URL, "http://localhost:" + mockServerRule.getPort() + "/email/classification/predict")
.setProperty(SERVICE_USERNAME, "username")
.setProperty(SERVICE_PASSWORD, "password")
.build();
GuessClassificationMailet testee = new GuessClassificationMailet(new FakeUUIDGenerator());
testee.init(config);
InputStream systemResourceAsStream = ClassLoader.getSystemResourceAsStream("eml/utf8.eml");
MimeMessage mimeMessage = new MimeMessage(Session.getDefaultInstance(new Properties()), systemResourceAsStream);
FakeMail mail = FakeMail.builder()
.mimeMessage(mimeMessage)
.recipients(new MailAddress("[email protected]"), new MailAddress("[email protected]"))
.build();
testee.service(mail);
PerRecipientHeaders expected = new PerRecipientHeaders();
expected.addHeaderForRecipient(PerRecipientHeaders.Header.builder()
.name(HEADER_NAME_DEFAULT_VALUE)
.value("{\"mailboxId\":\"cfe49390-f391-11e6-88e7-ddd22b16a7b9\",\"mailboxName\":\"JAMES\",\"confidence\":50.07615280151367}")
.build(),
new MailAddress("[email protected]"));
assertThat(mail.getPerRecipientSpecificHeaders()).isEqualTo(expected);
}
示例14: sendAlert
import javax.mail.Session; //导入方法依赖的package包/类
@Override
public void sendAlert(Observable observable) throws AddressException, MessagingException {
if (observable instanceof AbstarctMower) {
AbstarctMower mower = (AbstarctMower) observable;
ArrayList<MowerPosition> positionHistory = mower.getPositionHistory();
SettingInterface settingLoader = SettingLoaderFactory.getSettingLoader(DEFAULT);
Properties props = new Properties();
props.put("mail.smtp.host", settingLoader.getSMTPServer());
props.put("mail.smtp.socketFactory.port", String.valueOf(settingLoader.getSMTPPort()));
props.put("mail.smtp.socketFactory.class", settingLoader.getSSLSocketFactory());
props.put("mail.smtp.auth", settingLoader.isAuthenticationRequired());
props.put("mail.smtp.port", String.valueOf(settingLoader.getSMTPPort()));
String password = PasswordDecrypt.getInstance().decrypt("HA%HYDG1;[email protected]", "84m6BrC?T^P*!#bz",
settingLoader.getPassword());
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(settingLoader.getUserName(), password);
}
});
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(settingLoader.getSender()));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(settingLoader.getUserName()));
String key0 = mower.getIdentifier();
String subject = MessageGetter.getMessage(EMAIL_ALERT_SUBJECT, new String[] { key0 });
message.setSubject(subject);
StringBuilder body = new StringBuilder();
for (int i = 1; i < positionHistory.size(); i++) {
MowerPosition mowerPosition = positionHistory.get(i);
body.append(mowerPosition.toString()).append(BR).append(BR);
}
String key1 = mower.getUpdateDate() != null ? mower.getUpdateDate().toString() : N_A;
String key2 = positionHistory.get(0) != null ? positionHistory.get(0).toString() : N_A;
String key3 = body.toString();
String bodyMessage = MessageGetter.getMessage(EMAIL_ALERT_MESSAGE, new String[] { key0, key1, key2, key3 });
message.setContent(bodyMessage, CONTENT_TYPE);
Transport.send(message);
}
}
示例15: testMessageRenamedBetweenReads
import javax.mail.Session; //导入方法依赖的package包/类
public void testMessageRenamedBetweenReads() throws Exception
{
// Get test message UID
final Long uid = getMessageUid(folder, 1);
// Get Message size
final int count = getMessageSize(folder, uid);
// Get first part
// Split the message into 2 part using a non multiple of 4 - 103 is a prime number
// as the BASE64Decoder may not throw the IOException
// see MNT-12995
BODY body = getMessageBodyPart(folder, uid, 0, count - 103);
// Rename message. The size of letter describing the node will change
// These changes should be committed because it should be visible from client
NodeRef contentNode = findNode(companyHomePathInStore + TEST_FILE);
UserTransaction txn = transactionService.getUserTransaction();
txn.begin();
fileFolderService.rename(contentNode, "testtesttesttesttesttesttesttesttesttest");
txn.commit();
// Read second message part
BODY bodyRest = getMessageBodyPart(folder, uid, count - 103, 103);
// Creating and parsing message from 2 parts
MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()), new SequenceInputStream(new BufferedInputStream(body.getByteArrayInputStream()),
new BufferedInputStream(bodyRest.getByteArrayInputStream())));
// Reading first part - should be successful
MimeMultipart content = (MimeMultipart) message.getContent();
assertNotNull(content.getBodyPart(0).getContent());
try
{
// Reading second part cause error
content.getBodyPart(1).getContent();
fail("Should raise an IOException");
}
catch (IOException e)
{
}
}