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


Scala Session类代码示例

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


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

示例1: Mailer

//设置package包名称以及导入依赖的类
package org.kirhgoff.lastobot

import java.util.Properties
import javax.mail.{Message, Session}
import javax.mail.internet.{InternetAddress, MimeMessage}

import scala.io.Source


object Mailer {
  val host = "smtp.gmail.com"
  val port = "587"

  val address = "[email protected]"
  val username = "lastobot"
  val password = Source.fromFile(System.getProperty("user.home")
    + "/.lastobot/.mail").getLines.mkString

  def sendMail(text:String, subject:String) = {
    val properties = new Properties()
    properties.put("mail.smtp.port", port)
    properties.put("mail.smtp.auth", "true")
    properties.put("mail.smtp.starttls.enable", "true")

    val session = Session.getDefaultInstance(properties, null)
    val message = new MimeMessage(session)
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(address));
    message.setSubject(subject)
    message.setContent(text, "text/html")

    val transport = session.getTransport("smtp")
    transport.connect(host, username, password)
    transport.sendMessage(message, message.getAllRecipients)
  }

  def main(args:Array[String]) = {
    sendMail("aaaa", "bbb")
  }
} 
开发者ID:kirhgoff,项目名称:lastobot,代码行数:40,代码来源:Mailer.scala

示例2: EmailParser

//设置package包名称以及导入依赖的类
package uk.pkerrigan.dmarcparser

import java.io.ByteArrayInputStream
import java.nio.charset.CodingErrorAction
import java.util.Properties
import java.util.zip.{GZIPInputStream, ZipInputStream}
import javax.activation.DataSource
import javax.mail.Session
import javax.mail.internet.MimeMessage
import scala.collection.JavaConverters._

import org.apache.commons.mail.util.MimeMessageParser
import uk.pkerrigan.dmarcparser.report.Feedback

import scala.io._

class EmailParser(parser: ParserTrait = new Parser()) extends EmailParserTrait{

  implicit val codec = Codec("UTF-8")
  codec.onMalformedInput(CodingErrorAction.REPLACE)
  codec.onUnmappableCharacter(CodingErrorAction.REPLACE)

  def parseEmail(email: String): Option[Feedback] = {
    val s = Session.getDefaultInstance(new Properties())
    val is = new ByteArrayInputStream(email.getBytes)
    val message = new MimeMessage(s, is)
    val messageParser = new MimeMessageParser(message).parse()

    messageParser.getAttachmentList.asScala.headOption.flatMap(extract)
  }

  private def extract(a: DataSource): Option[Feedback] = a match {
    case `a` if a.getContentType.equals("application/gzip") => extractGzip(a)
    case `a` if a.getContentType.equals("application/x-gzip") => extractGzip(a)
    case `a` if a.getContentType.equals("application/zip") => extractZip(a)
    case `a` if a.getContentType.equals("application/x-zip-compressed") => extractZip(a)
    case _ => None
  }

  private def extractZip(a: DataSource): Option[Feedback] = {
    val zip = new ZipInputStream(a.getInputStream)
    zip.getNextEntry
    val rawXml = Source.fromInputStream(zip).mkString
    if (rawXml == "") None else Some(parser.parse(rawXml))
  }
  private def extractGzip(a: DataSource): Option[Feedback] = {
    val zip = new GZIPInputStream(a.getInputStream)
    val rawXml = Source.fromInputStream(zip).mkString
    if (rawXml == "") None else Some(parser.parse(rawXml))
  }
} 
开发者ID:patrickkerrigan,项目名称:dmarc-parser,代码行数:52,代码来源:EmailParser.scala

示例3: SessionFactory

//设置package包名称以及导入依赖的类
package com.github.jurajburian.mailer

import java.util.Properties
import javax.mail.{PasswordAuthentication, Authenticator, Session}

import scala.annotation.tailrec



object SessionFactory {
	def apply() = new SessionFactory {
		override def append(p: Prop): SessionFactory = {
			@tailrec
			def walk(p: impl, properties: Properties = new Properties()): Properties = {
				p.prop.convert.map { p => properties.setProperty(p._1, p._2.toString) }
				if (p.prev == null) {
					properties
				} else {
					walk(p.prev, properties)
				}
			}
			case class impl(prev: impl, val prop: Prop) extends SessionFactory {
				override def append(p: Prop): SessionFactory = new impl(this, p)

				def properties(): Properties = {
					walk(this)
				}

				override def session(credentials: Option[(String, String)] = None): Session = {
					val ps = properties()
					credentials match {
						case None => {
							Session.getInstance(ps)
						}
						case Some((u, p)) => {
							ps.put("mail.smtp.auth", true.toString)
							Session.getInstance(ps, new Authenticator {
								protected override def getPasswordAuthentication() = new PasswordAuthentication(u, p)
							})
						}
					}
				}
			}
			impl(null, p)
		}

		override def session(credentials: Option[(String, String)] = None): Session = {
			throw new NotImplementedError()
		}
	}
} 
开发者ID:JurajBurian,项目名称:mailer,代码行数:52,代码来源:SessionFactory.scala

示例4: MailServerInfo

//设置package包名称以及导入依赖的类
package com.ox.bigdata.util.mail

import java.util.Properties
import javax.mail.{Authenticator, PasswordAuthentication, Session}


case class MailServerInfo(mailServerHost: String, mailServerPort: String, isAuthenticated: String, isEnabledDebugMod: String, userName: String, passWord: String)

class MailServer(mailServerInfo: MailServerInfo) {

  private class MailAuthenticator(userName: String, passWord: String) extends Authenticator {
    override protected def getPasswordAuthentication: PasswordAuthentication = new PasswordAuthentication(userName, passWord)
  }

  private def getSystemProperties: Properties = {
    val sysProperties = new Properties()
    //    sysProperties.setProperty("mail.transport.protocol", "smtp")
    sysProperties.put("mail.smtp.host", mailServerInfo.mailServerHost)
    sysProperties.put("mail.smtp.port", mailServerInfo.mailServerPort)
    sysProperties.put("mail.smtp.auth", mailServerInfo.isAuthenticated)
    sysProperties.put("mail.debug", mailServerInfo.isEnabledDebugMod)
    sysProperties
  }

  private def getAuthenticator: Option[Authenticator] = {
    if (mailServerInfo.isAuthenticated == "true")
      Some(new MailAuthenticator(mailServerInfo.userName, mailServerInfo.passWord))
    else None
  }

  // mail session
  def getMailSession: Session = getAuthenticator match {
    case Some(authenticator) => Session.getInstance(getSystemProperties, authenticator)
    case None => Session.getDefaultInstance(getSystemProperties)
  }
} 
开发者ID:black-ox,项目名称:simple,代码行数:37,代码来源:MailServer.scala

示例5: send

//设置package包名称以及导入依赖的类
package com.github.cuzfrog.maila.server

import java.util.Date
import javax.mail.Message.RecipientType
import javax.mail.internet.{InternetAddress, MimeMessage}
import javax.mail.{Address, MessagingException, Session, Transport}

private[server] trait Sender {
  def send(recipients: Seq[String], subject: String, text: String): (Boolean, String)

  def close(): Unit
}

private[server] object Sender {
  def apply(session: Session, transport: Transport, user: String): Sender = new JmSender(session, transport, user)

  private class JmSender(session: Session, transport: Transport, user: String) extends Sender {

    def send(recipients: Seq[String], subject: String, text: String): (Boolean, String) = {
      val addresses: Array[Address] = recipients.map(new InternetAddress(_)).toArray
      val message = new MimeMessage(session)
      message.setFrom(new InternetAddress(user))

      message.addRecipients(RecipientType.TO, addresses)
      message.setSubject(subject)
      message.setText(text)
      message.setSentDate(new Date())
      val msg = s"Sent message[${message.getSubject}] to[${message.getAllRecipients.mkString(",")}]"
      try {
        transport.sendMessage(message, message.getAllRecipients)
        (true, s"$msg successfully.")
      } catch {
        case e: MessagingException =>
          (false, s"$msg Failed with msg:${e.getMessage}")
      }
    }

    def close(): Unit = transport.close()
  }

} 
开发者ID:cuzfrog,项目名称:maila,代码行数:42,代码来源:Sender.scala

示例6: reader

//设置package包名称以及导入依赖的类
package com.github.cuzfrog.maila.server

import javax.mail.Session

import com.github.cuzfrog.maila.Configuration

private[maila] trait Server {
  def reader: Reader

  def sender: Sender
}

private[maila] object Server {
  def apply(config: Configuration): Server = {
    new JmServer(config)
  }

  private class JmServer(config: Configuration) extends Server {
    val properties = config.serverProps
    lazy val session = Session.getInstance(properties)
    session.setDebug(config.javaMailDebug)
    lazy val store = session.getStore(config.storeType)
    lazy val transport = session.getTransport(config.transportType)

    def reader = {
      store.connect(config.user, config.password)
      Reader(store, config)
    }

    def sender = {
      transport.connect(config.user, config.password)
      Sender(session, transport, config.user)
    }
  }

} 
开发者ID:cuzfrog,项目名称:maila,代码行数:37,代码来源:Server.scala

示例7: MailConfig

//设置package包名称以及导入依赖的类
package services.Mail

import javax.mail.search.SearchTerm
import javax.mail.{Folder, Message, Session, Store}

import com.typesafe.config.{Config, ConfigFactory}



object MailConfig{
  def default(): MailConfig = {
    val session = Session.getDefaultInstance(System.getProperties)
    val store = session.getStore("imaps")
    new MailConfig(
      store
      ,ConfigFactory.load
    )
  }
}

class MailConfig private(s: Store, c: Config){
  protected var folder: Folder = null
  protected val store : Store = s
  protected val config : Config = c

  def open() = {
    this.store.connect("imap.gmail.com", config.getString("gmail.address"), config.getString("gmail.password"))
    this.folder = store.getFolder(config.getString("gmail.folder"))
    this.folder.open(Folder.READ_ONLY)
  }
  def close() = {
    this.folder.close(true)
    this.store.close()
  }
  def search(term: SearchTerm): Seq[Message] = {
    this.folder.search(term)
  }
} 
开发者ID:ShotaOda,项目名称:scala-slick-backbone,代码行数:39,代码来源:MailConfig.scala

示例8: sendMail

//设置package包名称以及导入依赖的类
package wuxi99
import javax.mail.Message
import javax.mail.Session
import javax.mail.Transport
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeMessage
import java.util.Date
import java.util.Properties
import grizzled.slf4j.Logger
trait Email {
	def sendMail(mailTitle:String,mailContent:String)
	def sendMailFL(mailTitle:String,fileName:String,line:Int,AppCount:Int){
		val mailContent = s"""<b>??:${fileName}</b><br>
			<b>??:${line}</b><br>
			<b>???:${AppCount}</b>"""
		sendMail(mailTitle,mailContent)
	}
 def sendMailHtml(mailTitle:String,mailContent:String){
    val mailContentHtml = s"<b>${mailContent}</b>"
    sendMail(mailTitle,mailContentHtml)
  }
}

object MailUtility extends Email {
	private val smtpServer = "smtp.exmail.qq.com"
	private val fromMail = "[email protected]"
	private val toMail = "[email protected]"
	private val user = fromMail
	private val password = "ys123456"
	@transient lazy val logger = Logger[this.type]


	def sendMail(mailTitle:String,mailContent:String) {
	  try {	
		val props = new Properties()
		props.put("mail.smtp.host",smtpServer )
		props.put("mail.smtp.auth", "true")
		val session = Session.getInstance(props)

		val message = new MimeMessage(session)
		message.setFrom(new InternetAddress(fromMail))
		message.setRecipient(Message.RecipientType.TO, new InternetAddress(toMail))
		message.setSubject(mailTitle)
		message.setContent(mailContent, "text/html;charset=utf-8")
		//message.setText(mailContent)
		message.setSentDate(new Date())
		message.saveChanges()

		val transport = session.getTransport("smtp")
		transport.connect(user, password)
		transport.sendMessage(message, message.getAllRecipients())
		transport.close()
	  } catch {
		case _ : Throwable => logger.info("This Mail Didnot Send:[ " + mailTitle + " ] [ " + mailContent + "]" )
          }	
	}

} 
开发者ID:yangshuxuan,项目名称:OptFoatSalesWithSparkAndScala,代码行数:59,代码来源:mailUtility.scala


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