下面列出了javax.mail.internet.MimeMessage#setText ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void sendEmail(String email, String subjectline, String content) throws UnsupportedEncodingException{
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(
Configurations.getConfigurationProperty("poc.cfg.property.smtp.from"),
Configurations.getConfigurationProperty("poc.cfg.property.smtp.fromName")));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
message.setSubject(subjectline);
if(Configurations.getConfigurationProperty("poc.cfg.property.email.type").equalsIgnoreCase("HTML")){
message.setContent(content, "text/html; charset=utf-8");
}
else{
message.setText(content);
}
Transport.send(message);
} catch (MessagingException ex) {
ex.printStackTrace();
POCLogger.logp(Level.SEVERE, CLASSNAME, "callSKFSRestApi", "POC-ERR-5001", ex.getLocalizedMessage());
}
}
@Test
void serviceShouldReplaceBodyWhenMatching() throws Exception {
FakeMailetConfig mailetConfig = FakeMailetConfig.builder()
.mailetName("Test")
.setProperty("bodyPattern",
"/test/TEST/i/," +
"/o/a/r/," +
"/S/s/r/,/è/e'//," +
"/test([^\\/]*?)bla/X$1Y/im/," +
"/X(.\\n)Y/P$1Q//," +
"/\\/\\/,//")
.build();
mailet.init(mailetConfig);
MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));
message.setText("This is one simple test/ è one simple test.\n"
+ "Blo blo blo blo.\n");
Mail mail = FakeMail.builder()
.name("mail")
.mimeMessage(message)
.build();
mailet.service(mail);
assertThat(mail.getMessage().getContent()).isEqualTo("This is ane simple TEsT, e' ane simple P.\n"
+ "Q bla bla bla.\n");
}
@Override
public void sendEmail(String address, String subject, String content, Map<String, String> headers,
UnaryOperator<String> properties) throws Exception {
Session session = MailUtilities.makeSession(properties);
if (session == null) {
LogService.getRoot().log(Level.WARNING, SESSION_CREATION_FAILURE, address);
}
MimeMessage msg = new MimeMessage(session);
msg.setRecipients(Message.RecipientType.TO, address);
msg.setFrom();
msg.setSubject(subject, "UTF-8");
msg.setSentDate(new Date());
msg.setText(content, "UTF-8");
if (headers != null) {
for (Entry<String, String> header : headers.entrySet()) {
msg.setHeader(header.getKey(), header.getValue());
}
}
Transport.send(msg);
}
@Test
public void test3SendMessage() throws Exception {
Session.getDefaultInstance(getProperties());
final MimeMessage msg = new MimeMessage((Session) null);
msg.setSubject("Test 1");
msg.setFrom("[email protected]");
msg.setText("Some text here ...");
msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
Transport.send(msg);
final Store store = session.getStore("mock_pop3");
store.connect("[email protected]", null);
final Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Assert.assertEquals(1, inbox.getMessageCount());
Assert.assertNotNull(inbox.getMessage(1));
Assert.assertEquals("Test 1", inbox.getMessage(1).getSubject());
inbox.close(false);
}
/**
* Create a MimeMessage using the parameters provided.
*
* @param to Email address of the receiver.
* @param from Email address of the sender, the mailbox account.
* @param subject Subject of the email.
* @param bodyText Body text of the email.
* @return MimeMessage to be used to send email.
* @throws MessagingException
*/
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);
InternetAddress tAddress = new InternetAddress(to);
InternetAddress fAddress = new InternetAddress(from);
email.setFrom(new InternetAddress(from));
email.addRecipient(javax.mail.Message.RecipientType.TO,
new InternetAddress(to));
email.setSubject(subject);
email.setText(bodyText);
return email;
}
@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);
}
}
public static void main_send_by_concept() {
String fromMail = "";
String toMail = "";
String subject = "Тестовый заголовок";
String text = "<html><body><h1>Тест</h1><p>Тест отправки письма</body></html>";
String username = "";
String password = "";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromMail));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toMail));
message.setSubject(subject);
message.setText(text, "UTF-8", "html");
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
/**
* Method to send simple HTML email
*/
private void sendEmail() {
Logger logger = Logger.getLogger("Mail Error");
try {
MimeMessage msg = new MimeMessage(session);
// set message headers
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
msg.setFrom(new InternetAddress(toEmail, "MZmine"));
msg.setSubject(subject, "UTF-8");
msg.setText("MZmine has detected an error :\n" + body, "UTF-8");
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
Transport.send(msg);
logger.info("Successfully sended error mail: " + subject + "\n" + body);
} catch (Exception e) {
logger.info("Failed sending error mail:" + subject + "\n" + body);
e.printStackTrace();
}
}
@Override
public JetstreamEvent processMetaInformation(JetstreamEvent event,
StatementAnnotationInfo annotationInfo) {
SendMailAnnotationMetadata anntmetadata = (SendMailAnnotationMetadata) annotationInfo.getAnnotationInfo(ANNO_KEY);
properties = new Properties();
properties.setProperty("mail.smtp.host", anntmetadata.getMailServer());
Session session = Session.getInstance(properties, null);
try{
MimeMessage message = new MimeMessage(session);
message.addHeader("Content-type", "text/HTML; charset=UTF-8");
message.setFrom(new InternetAddress(anntmetadata.getSendFrom()));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(anntmetadata.getAlertList(), false));
String[] fieldList = anntmetadata.getEventFields().split(",");
StringBuffer sb = new StringBuffer();
sb.append(anntmetadata.getMailContent()).append(".\n");
for(int i=0; i<fieldList.length;i++){
sb.append(fieldList[i]).append(": ").append(event.get(fieldList[i])).append(",\n");
}
message.setText(sb.toString(), "UTF-8");
StringBuffer subject = new StringBuffer();
if(anntmetadata.getAlertSeverity() != null)
subject.append(anntmetadata.getAlertSeverity()).append(" alert for Jetstream Event Type").append(event.getEventType()).append(": ");
if(anntmetadata.getMailSubject() != "")
subject.append(anntmetadata.getMailSubject());
message.setSubject(subject.toString(), "UTF-8");
Transport.send(message);
}catch (Throwable mex) {
s_logger.warn( mex.getLocalizedMessage());
}
return event;
}
public static void main(String[] args) throws Exception {
Properties prop = new Properties();
prop.setProperty("mail.debug", "true");
prop.setProperty("mail.host", MAIL_SERVER_HOST);
prop.setProperty("mail.transport.protocol", "smtp");
prop.setProperty("mail.smtp.auth", "true");
// 1、创建session
Session session = Session.getInstance(prop);
Transport ts = null;
// 2、通过session得到transport对象
ts = session.getTransport();
// 3、连上邮件服务器
ts.connect(MAIL_SERVER_HOST, USER, PASSWORD);
// 4、创建邮件
MimeMessage message = new MimeMessage(session);
// 邮件消息头
message.setFrom(new InternetAddress(MAIL_FROM)); // 邮件的发件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(MAIL_TO)); // 邮件的收件人
message.setRecipient(Message.RecipientType.CC, new InternetAddress(MAIL_CC)); // 邮件的抄送人
message.setRecipient(Message.RecipientType.BCC, new InternetAddress(MAIL_BCC)); // 邮件的密送人
message.setSubject("测试文本邮件"); // 邮件的标题
// 邮件消息体
message.setText("天下无双。");
// 5、发送邮件
ts.sendMessage(message, message.getAllRecipients());
ts.close();
}
public void addMessage(String testName, GreenMailUser user) throws MessagingException {
Properties prop = new Properties();
Session session = Session.getDefaultInstance(prop);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
message.setSubject("Test email" + testName);
message.setText("test test test chocolate");
user.deliver(message);
}
private static MimeMessage createSimpleMail(Session session, String theme, String messages,String email) throws Exception {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.addRecipients(Message.RecipientType.TO, email);
message.setSubject(theme);
message.setText(messages);
message.saveChanges();
return message;
}
@Test
// (expected = MockTestException.class)
public void testAppendFailMessage() throws Exception {
final MockMailbox mb = MockMailbox.get("[email protected]");
final MailboxFolder mf = mb.getInbox();
final MimeMessage msg = new MimeMessage((Session) null);
msg.setSubject("Test");
msg.setFrom("[email protected]");
msg.setText("Some text here ...");
msg.setRecipient(RecipientType.TO, new InternetAddress("hend[email protected]"));
mf.add(msg); // 11
mf.add(msg); // 12
mf.add(msg); // 13
mb.getRoot().getOrAddSubFolder("test").create().add(msg);
final Store store = session.getStore();
store.connect("[email protected]", null);
final Folder defaultFolder = store.getDefaultFolder();
final Folder inbox = defaultFolder.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
try {
inbox.appendMessages(new MimeMessage[] { msg });
} catch (final IllegalStateException e) {
// throw new MockTestException(e);
}
// Assert.fail("Exception expected before this point");
Assert.assertEquals(4, inbox.getMessageCount());
inbox.close(false);
}
public void send(String to, String title, String message) throws Exception {
Session session = Session.getDefaultInstance(properties, getAuthenticator());
// Create a default MimeMessage object.
MimeMessage mimeMessage = new MimeMessage(session);
// Set From: header field of the header.
mimeMessage.setFrom(new InternetAddress(adminAddress));
// Set To: header field of the header.
mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set Subject: header field
mimeMessage.setSubject(title);
// Now set the actual message
mimeMessage.setText(message);
// Send message
Transport.send(mimeMessage);
}
@ParameterizedTest
@ValueSource(strings = {PKCS1_PEM_FILE, PKCS8_PEM_FILE})
void testDKIMSignMessageAsText(String pemFile) throws MessagingException,
IOException, FailException {
MimeMessage mm = new MimeMessage(Session
.getDefaultInstance(new Properties()));
mm.addFrom(new Address[]{new InternetAddress("[email protected]")});
mm.addRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
mm.setText("An 8bit encoded body with €uro symbol.", "ISO-8859-15");
Mailet mailet = new DKIMSign();
FakeMailetConfig mci = FakeMailetConfig.builder()
.mailetName("Test")
.mailetContext(FAKE_MAIL_CONTEXT)
.setProperty(
"signatureTemplate",
"v=1; s=selector; d=example.com; h=from:to:received:received; a=rsa-sha256; bh=; b=;")
.setProperty("privateKeyFilepath", pemFile)
.build();
mailet.init(mci);
Mail mail = FakeMail.builder()
.name("test")
.mimeMessage(mm)
.build();
Mailet m7bit = new ConvertTo7Bit();
m7bit.init(mci);
mailet.service(mail);
m7bit.service(mail);
ByteArrayOutputStream rawMessage = new ByteArrayOutputStream();
mail.getMessage().writeTo(rawMessage);
MockPublicKeyRecordRetriever mockPublicKeyRecordRetriever = new MockPublicKeyRecordRetriever(
"v=DKIM1; k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDYDaYKXzwVYwqWbLhmuJ66aTAN8wmDR+rfHE8HfnkSOax0oIoTM5zquZrTLo30870YMfYzxwfB6j/Nz3QdwrUD/t0YMYJiUKyWJnCKfZXHJBJ+yfRHr7oW+UW3cVo9CG2bBfIxsInwYe175g9UjyntJpWueqdEIo1c2bhv9Mp66QIDAQAB;",
"selector", "example.com");
verify(rawMessage, mockPublicKeyRecordRetriever);
}
/**
* Sets the content for a message. Also attaches files to the message.
* @throws MessagingException
*/
protected void setContent(String content, List<Attachment> attachments, MimeMessage msg,
String contentType, String charset, String multipartSubtype) throws AttachmentSizeException, MessagingException {
ArrayList<MimeBodyPart> embeddedAttachments = new ArrayList<MimeBodyPart>();
if (attachments != null && attachments.size() > 0) {
int maxAttachmentSize = serverConfigurationService.getInt(MAIL_SENDFROMSAKAI_MAXSIZE, DEFAULT_MAXSIZE);
long attachmentRunningTotal = 0L;
// Add attachments to messages
for (Attachment attachment : attachments) {
// attach the file to the message
MimeBodyPart mbp = createAttachmentPart(attachment);
long mbpSize = (long) mbp.getSize();
if (mbpSize == -1L) {
// This is normal. See MimeBodyPart documentation.
mbpSize = attachment.getSizeIfFile().orElse(-1L);
}
if (mbpSize == -1L) {
log.warn("Failed to get size of email attachment. This could result in the limit being exceeded");
}
if ( (attachmentRunningTotal + mbpSize) < maxAttachmentSize ) {
embeddedAttachments.add(mbp);
attachmentRunningTotal = attachmentRunningTotal + mbpSize;
} else {
throw new AttachmentSizeException("Attachments too large", attachmentRunningTotal + mbpSize);
}
}
}
// if no direct attachments, keep the message simple and add the content as text.
if (embeddedAttachments.size() == 0) {
// if no contentType specified, go with text/plain
if (contentType == null) {
msg.setText(content, charset);
} else {
msg.setContent(content, contentType);
}
} else {
// the multipart was constructed (ie. attachments available), use it as the message content
// create a multipart container
Multipart multipart = (multipartSubtype != null) ? new MimeMultipart(multipartSubtype) : new MimeMultipart();
// create a body part for the message text
MimeBodyPart msgBodyPart = new MimeBodyPart();
if (contentType == null) {
msgBodyPart.setText(content, charset);
} else {
msgBodyPart.setContent(content, contentType);
}
// add the message part to the container
multipart.addBodyPart(msgBodyPart);
// add attachments
for (MimeBodyPart attachPart : embeddedAttachments) {
multipart.addBodyPart(attachPart);
}
// set the multipart container as the content of the message
msg.setContent(multipart);
}
}
@Override
public void send(InternetAddress address, String subject, String htmlBody)
throws AddressException, MessagingException {
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, address);
message.setSubject(subject);
message.setText(htmlBody, "UTF-8", "html");
LOG.info("Sending email:" + "\n Subject: " + subject + "\n Message body: " + htmlBody);
// Send message
Transport.send(message);
}
/**
* Sets the content for a message. Also attaches files to the message.
* @throws MessagingException
*/
protected void setContent(String content, List<Attachment> attachments, MimeMessage msg,
String contentType, String charset, String multipartSubtype) throws AttachmentSizeException, MessagingException {
ArrayList<MimeBodyPart> embeddedAttachments = new ArrayList<MimeBodyPart>();
if (attachments != null && attachments.size() > 0) {
int maxAttachmentSize = serverConfigurationService.getInt(MAIL_SENDFROMSAKAI_MAXSIZE, DEFAULT_MAXSIZE);
long attachmentRunningTotal = 0L;
// Add attachments to messages
for (Attachment attachment : attachments) {
// attach the file to the message
MimeBodyPart mbp = createAttachmentPart(attachment);
long mbpSize = (long) mbp.getSize();
if (mbpSize == -1L) {
// This is normal. See MimeBodyPart documentation.
mbpSize = attachment.getSizeIfFile().orElse(-1L);
}
if (mbpSize == -1L) {
log.warn("Failed to get size of email attachment. This could result in the limit being exceeded");
}
if ( (attachmentRunningTotal + mbpSize) < maxAttachmentSize ) {
embeddedAttachments.add(mbp);
attachmentRunningTotal = attachmentRunningTotal + mbpSize;
} else {
throw new AttachmentSizeException("Attachments too large", attachmentRunningTotal + mbpSize);
}
}
}
// if no direct attachments, keep the message simple and add the content as text.
if (embeddedAttachments.size() == 0) {
// if no contentType specified, go with text/plain
if (contentType == null) {
msg.setText(content, charset);
} else {
msg.setContent(content, contentType);
}
} else {
// the multipart was constructed (ie. attachments available), use it as the message content
// create a multipart container
Multipart multipart = (multipartSubtype != null) ? new MimeMultipart(multipartSubtype) : new MimeMultipart();
// create a body part for the message text
MimeBodyPart msgBodyPart = new MimeBodyPart();
if (contentType == null) {
msgBodyPart.setText(content, charset);
} else {
msgBodyPart.setContent(content, contentType);
}
// add the message part to the container
multipart.addBodyPart(msgBodyPart);
// add attachments
for (MimeBodyPart attachPart : embeddedAttachments) {
multipart.addBodyPart(attachPart);
}
// set the multipart container as the content of the message
msg.setContent(multipart);
}
}
/**
* @return the message to send
* @throws MessagingException
*/
Message getMessageToSend() throws MessagingException {
// Subject and message
Properties mailProperties = this.manager.preferencesMngr().getJavaxMailProperties();
String subject = "Roboconf event";
String data = this.instr.getMsg();
final String emailSubjectPattern = "Subject: ([^\n]+)(\n|$)(.*)";
Matcher m = Pattern.compile( emailSubjectPattern ).matcher( this.instr.getMsg());
if( m.find()) {
subject = m.group( 1 );
data = m.group( 3 ).trim();
}
// Credentials
String username = mailProperties.getProperty( IPreferencesMngr.JAVAX_MAIL_SMTP_USER, "" );
String password = mailProperties.getProperty( IPreferencesMngr.JAVAX_MAIL_SMTP_PWD, "" );
// Obtain mail session object
Session session = null;
if("true".equalsIgnoreCase( mailProperties.getProperty( IPreferencesMngr.JAVAX_MAIL_SMTP_AUTH )))
session = Session.getInstance( mailProperties, new MailAuthenticator( username, password ));
else
session = Session.getDefaultInstance( mailProperties );
// Create a default MimeMessage object
MimeMessage message = new MimeMessage(session);
// Set From: and To: header fields
message.setFrom( new InternetAddress( mailProperties.getProperty( IPreferencesMngr.JAVAX_MAIL_FROM )));
Set<String> tos = new LinkedHashSet<> ();
tos.addAll( this.instr.getTos());
String defaultRecipients = this.manager.preferencesMngr().get( IPreferencesMngr.EMAIL_DEFAULT_RECIPIENTS, "" );
List<String> recipients = Utils.splitNicely( defaultRecipients, "," );
tos.addAll( recipients );
for( String to : tos )
message.addRecipient( Message.RecipientType.TO, new InternetAddress( to ));
message.setSubject( subject );
message.setText( data.trim());
return message;
}
private static com.google.api.services.gmail.model.Message createMessage(String to, String from, String subject,
String bodyText, String cc, String bcc) throws MessagingException, IOException {
if (ObjectHelper.isEmpty(to)) {
throw new RuntimeCamelException("Cannot create gmail message as no 'to' address is available");
}
if (ObjectHelper.isEmpty(from)) {
throw new RuntimeCamelException("Cannot create gmail message as no 'from' address is available");
}
if (ObjectHelper.isEmpty(subject)) {
LOG.warn("New gmail message wil have no 'subject'. This may not be want you wanted?");
}
if (ObjectHelper.isEmpty(bodyText)) {
LOG.warn("New gmail message wil have no 'body text'. This may not be want you wanted?");
}
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
MimeMessage email = new MimeMessage(session);
email.setFrom(new InternetAddress(from));
email.addRecipients(javax.mail.Message.RecipientType.TO, getAddressesList(to));
email.setSubject(subject);
email.setText(bodyText);
if (ObjectHelper.isNotEmpty(cc)) {
email.addRecipients(javax.mail.Message.RecipientType.CC, getAddressesList(cc));
}
if (ObjectHelper.isNotEmpty(bcc)) {
email.addRecipients(javax.mail.Message.RecipientType.BCC, getAddressesList(bcc));
}
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
email.writeTo(buffer);
byte[] bytes = buffer.toByteArray();
String encodedEmail = Base64.encodeBase64URLSafeString(bytes);
com.google.api.services.gmail.model.Message message = new com.google.api.services.gmail.model.Message();
message.setRaw(encodedEmail);
return message;
}